Regex match optional string greedy inbetween two random strings

Viewed 57

I am looking for a way to match an optional ABC in the following strings. Both strings should be matched either way, if ABC is there or not:

precedingstringwithundefinedlenghtABCsubsequentstringwithundefinedlength precedingstringwithundefinedlenghtsubsequentstringwithundefinedlength

I've tried

.*(ABC).*

which doesn't work for an optional ABC but making ABC non greedy doesn't work either as the .* will take all the pride:

.*(ABC)?.*

This is NOT a duplicate to e.g. Regex Match all characters between two strings as I am looking for a certain string inbetween two random string, kind of the other way around.

4 Answers

You can use

.*(ABC).*|.*

This works like this:

  • .*(ABC).* pattern is searched for first, since it is the leftmost part of an alternation (see "Remember That The Regex Engine Is Eager"), it looks for any zero or more chars other than line break chars as many as possible, then captures ABC into Group 1 and then matches the rest of the line with the right-hand .*
  • | - or
  • .* - is searched for if the first alternation part does not match.

Another solution without the need to use alternation:

^(?:.*(ABC))?.*

See this regex demo. Details:

  • ^ - start of string
  • (?:.*(ABC))? - an optional non-capturing group that matches zero or more chars other than line break chars as many as possible and then captures into Group 1 an ABC char sequence
  • .* - zero or more chars other than line break chars as many as possible.

I’ve come up with an answer myself: Using the OR operator seems to work:

(?:(?:.*(ABC))|.*).*

If there’s a better way, feel free to answer and I will accept it.

You could use this regex: .*(ABC){0,1}.*. It means any, optional{min,max}, any. It is easier to read. I can' t say if your solution or mine is faster due to the processing speed. Options: {value} = n-times {min,} = min to infinity {min,max} = min to max

Related