How to simulate non-greedy quantifiers in languages โ€‹โ€‹that do not support them?

Consider this regular expression: <(.*)>

Applies to this line:

<2356> <my pal ned> < !@ %@>

Obviously, it will match the entire line due to the greedy * . A better solution would be to use a non-greedy quantifier like *? . However, many languages โ€‹โ€‹and editors do not support them.

For simple cases like the ones above, I limited this restriction to a regular expression as follows: <([^>]*)>

But what can be done with regex? start (.*) end

Applies to this line:

start 2356 end start my pal ned end start !@ %@ end

Is there any regression?

+4
source share
2 answers

If the final condition is to have one character, you can use a negative character class instead:

 <([^>]*)> 

For more complex cases, when the final condition is multiple characters, you can try a negative lookup, but if lazy matching is not supported, the likelihood that lookaheads will not be:

 ((?!end).)* 

The last resort is to build something terrible like this:

 (en[^d]|e[^n]|[^e])* 
+5
source

I am replacing . on [^>] , where > in this case is the next character in RE.

+2
source