Return to top of line in RegEx

Is it possible to put RegEx at the beginning of the line and start matching again?

That is why I ask. Given the line below, I would like to grab the substrings black , red , blue and green in that order, regardless of the order in which the subject appears in the string, and only if all the substrings are present in the subject line.

$str ='blue-ka93-red-kdke3-green-weifk-black'

So, for all the lines below, RegEx should capture black , red , blue and green (in that order)

 'blue-ka93-red-kdke3-green-weifk-black' 'green-ka93-red-kdke3-blue-weifk-black' 'blue-ka93-black-kdke3-green-weifk-red' 'green-ka93-black-kdke3-blue-weifk-red' 

I wonder if there is a way to map the capture group, and then go back to the beginning of the line and find the next capture group. I was hoping something like ^.*(?=(black))^.*(?=(red))^.*(?=(blue))^.*(?=(green)) would work but, of course, ^ and lookaheads do not behave this way.

Is it possible to build such a RegEx?

In context, I will use RegEx in PHP.

+5
source share
2 answers

you can use

 ^(?=.*(black))(?=.*(red))(?=.*(blue))(?=.*(green)) 

Note. This will require all of these keywords to be in a string.

Watch the demo

There is no way to reset the RegEx index when matching, so you can only use the capture mechanism inside the positive background fixed at the beginning. At the beginning of the line, an empty space at the beginning of the line will appear (due to ^ ), and each of them will look one after another if the previous one returns true (the text of the line matching its pattern was found).

Your RegEx didn’t work the same because you matched, consumed the text with .* (This subpattern was outside the lookaheads) and repeated the beginning of the line binding, which automatically fails with RegEx if you do not use a multi-line modifier.

+3
source

Why not just use capture groups to maintain order.

 ^(?:(black)|(red)|(blue)|(green)|.)+$ 

This will match any string, all colors are optional.

See demo in regex101 or php demo on eval.in

+1
source

Source: https://habr.com/ru/post/1241914/


All Articles