A regular expression that retrieves the last element starting with & [?

The regex should be applied to the following line:

[Product].[Product Catalog].[Product].&[50]&[53]&[DE]&[1ST_HQ]&[50_54_36]


The following regular expression is applied:



Which returns:



I want to change this regex to return



only. Any idea?


source to share

4 answers

You can just use the end of the $

anchor line if you want to retrieve the last element. Embedding Missing groups are not needed for these characters, so you can also delete groups.




&        # '&'
\[       # '['
 [^]]+   #    any character except: ']' (1 or more times)
]        # ']'
$        # before an optional \n, and the end of the string


Live Demo

Alternatively, I would suggest using a capture group to match and get a match result. .*

will contain all characters until the last occurrence &[

. Then you can refer to the group #1

for your match.





Use this regex:




indicates that the regex engine matches all and then falls back to match, so our match starts from the end of the line back and matches the last one. \K

keeps the match.

See the regex demo !



If you're using PCRE (or Ruby), you can do a dot-match and then go back to the last match &[...]

. Drop stuff to the left with \K





For a motor that doesn't support \K

, you can use a re-capture group. This requires you to turn .+

into lazy repetition with help ?

. The capture group will contain the contents of the last captured instance. This will match &[50]&[53]&[DE]&[1ST_HQ]&[50_54_36]

, but capture group 1 will be &[50_54_36]







Just use lookahead and replace .+







All Articles