Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fall back to begining of string in RegEx

Tags:

regex

php

Is it possible to have a RegEx fall back to the beginning of the string and begin matching again?

Here's why I ask. Given the below string, I'd like to capture the sub strings black, red, blue, and green in that order, regardless of the order of occurrence in the subject string and only if all substrings are present in the subject string.

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

So, for all of the below strings, the 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 isn't a way to match a capture group then fall back to the start of the string and find the next capture group. I was hoping that something like ^.*(?=(black))^.*(?=(red))^.*(?=(blue))^.*(?=(green)) would work but of course the ^ and lookaheads do not behave this way.

Is it possible to construct such a RegEx?

For context, I'll be using the RegEx in PHP.

like image 567
Wesley Smith Avatar asked Sep 25 '22 12:09

Wesley Smith


1 Answers

You can use

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

Note: This will require all these keywords to be in the string.

See demo

There is no way to reset RegEx index when matching, so, you can only use capturing mechanism inside a positive lookahead anchored at the start. The lookahead will match an empty location at the start of the string (due to ^) and each of tose lookaheads in the RegEx above will be executed one after another if the previous one returned true (found a string of text meeting its pattern).

Your RegEx did not work the same way because you matched, consumed the text with.* (this subpattern was outside the lookaheads) and repeated the start of string anchor that automatically fails a RegEx if you do not use a multiline modifier.

like image 80
Wiktor Stribiżew Avatar answered Oct 11 '22 14:10

Wiktor Stribiżew