Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression extracting last element starting with &[?

Tags:

regex

The regular Expression should be applied to the following string:

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

As-Is:
The following regular Expression is applied:

(?:&\[).+(?:\])

That Returns:

&[50]&[53]&[DE]&[1ST_HQ]&[50_54_36]

To-Be:
I want to Change that regular expression to return

&[50_54_36]

only. Any Idea?

like image 535
Patrick B. Avatar asked Jan 09 '23 19:01

Patrick B.


2 Answers

You could simply use the end of the string $ anchor if you want to extract the last element. Implementing Non-capturing groups for those characters is not necessary, so you can remove the groups as well.

&\[[^]]+]$

Explanation:

&        # '&'
\[       # '['
 [^]]+   #    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 capturing group to match and capture the match result. The .* here will eat up all characters up until the last occurrence of &[. You can then refer to group #1 for your match.

.*(&\[[^]]+])
like image 84
hwnd Avatar answered Jan 16 '23 02:01

hwnd


Use this regex:

.*\K&\[.+\]

The .* instructs the regex engine to match all, then backtrack to match, so our match will start from the end of the string backwards and match the last. \K keeps the match afterwards.

See a regex demo!

like image 41
Unihedron Avatar answered Jan 16 '23 03:01

Unihedron