Sonu Kumar
Sonu Kumar

Reputation: 108

Regex find match within a string

I have an example string:

Ole Abraham  of XYZ becomes Chief Digital Officer and EVP, Business Development of Warner Music Group.

I want all the words from the last occurrence of of till .. Result required: of Warner Music Group.

I have used the RegEx: (\bof\b).+\.\s? This is returning the sub-string from the first occurance of of:

of XYZ becomes Chief Digital Officer and EVP, Business Development of Warner Music Group. 

Upvotes: 3

Views: 164

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

Regex engines process the string from left to right, thus, the of your pattern matches is the first from the left. Then, .+ matches the whole line to its end, and only backtracks to find . (the \s? is not important, as it can match an empty string, but will be matched if found right after . since ? is a greedy quantifier).

You may use

.*\bof\s+([^.]+)

See the regex demo. The result will be in Group 1. Note that if you must test for the . presence in the string, append \. to the end of the pattern.

Details

  • .* - will match any 0+ chars other than line break chars, as many as possible, up to the last occurrence of the subsequent subpatterns
  • \bof - a whole word of
  • \s+ - 1 or more whitespaces
  • ([^.]+) - one or more chars other than ..

Upvotes: 2

Related Questions