I am searching in a string constructed somewhat like this:
bla bla bla *Priorities: bla bla - yada yada - Keyword, yada *Terms
and I can capture the Keywords like so:
\*Priorities:.*?-.*?- (.*?),.*?\*Terms
However in some cases there are more or less hyphens:
bla bla bla *Priorities: bla bla - yada yada - bla bla - Keyword, yada *Terms
I can get that too with:
\*Priorities:(.*?-){1,4} (.*?),.*?\*Terms
but I am trying to avoid a second capturing group (so I don't have to modify my code). Is there anyway to do this in some way that searches from the end of the pattern match to the last .?*-
? and still use the beginning of the string (*Priorities:
) in the pattern match and thus avoid a second capture group?
You can use this regex to match both input strings:
\*Priorities:.*- ([^,]*),.*?\*Terms
RegEx Breakup:
\*Priorities: # Match literal *Priorities:
.* # Match 0 or more any character (greedy match)
- # Match hyphen and space
([^,]*), # Match 0 or more of non-comma characters followed by a comma
.*? # Match 0 or more any character (lazy match)
\*Terms # Match literal *Terms
Note that due to lazy match .*
before hyphen+space we're making sure that we match longest match before last occurrence of hyphen+space.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments