Search code examples
regexbacktracking

Regex find match one word before and after the string encapsulated with {{ }}


example string:

Hi,
{{name}} from {{place}}  has closed your leave application (#2473)

here regex should match the words next and before curly braces globally.

for example.

for {{name}} it should match hi and from.

for {{place}} it should match from and has.

Regex I wrote:

/([^\ ]+?)? +?({{.+?}})[ \n]+([^\ {]+)?/iug

This is matching correctly if there are more than one word in between two curley braced items. If there is only 1 word it is causing issue.

Currently,

for {{name}} it matches hi and from. -- this is correclty

for {{place}} it matches has. -- this is wrong, it should match from also

REGEX101 link

https://regex101.com/r/wtyOIB/1

The original text for sample

Hi,

Vinod Sai from hyderabad has closed your leave application (#2473)

Solution

  • You may enclose the last part into a positive lookahead like this:

    (?:(\S+)\s+)?({{.*?}})(?=(?:\s+(\S+))?)
    

    See the regex demo

    Details

    • (?:(\S+)\s+)? - an optional non-capturing group that will match 1 or 0 occurrence of 1+ non-whitespace chars (captured into Group 1) and then 1+ whitespace chars
    • ({{.*?}}) - Group 2: {{, any 0+ chars other than line break chars, as few as possible
    • (?=(?:\s+(\S+))?) - a positive lookahead that will require an optional sequence of 1+ whitespace chars and 1+ non-whitespace chars immediately to the right of the current location while capturing the non-whitespace chars into Group 3, but forcing the regex index to remain where it was before trying to match the lookahead pattern since lookaheads are zero-width assertions.