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.
CodePudding user response:
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.
CodePudding user response:
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.