正则表达式查找匹配用{{}}封装的字符串前后的一个词
Regex find match one word before and after the string encapsulated with {{ }}
示例字符串:
Hi,
{{name}} from {{place}} has closed your leave application (#2473)
此处正则表达式应全局匹配花括号前和下一个单词。
例如。
for {{name}} it should match hi and from.
for {{place}} it should match from and has.
我写的正则表达式:
/([^\ ]+?)? +?({{.+?}})[ \n]+([^\ {]+)?/iug
如果两个大括号之间有一个以上的词,这就是正确匹配。如果只有 1 个字词,则会导致问题。
目前,
for {{name}} it matches hi and from. -- this is correclty
for {{place}} it matches has. -- this is wrong, it should match from also
REGEX101link
样本原文
Hi,
Vinod Sai from hyderabad has closed your leave application (#2473)
您可以像这样将最后一部分包含在积极的前瞻中:
(?:(\S+)\s+)?({{.*?}})(?=(?:\s+(\S+))?)
详情
(?:(\S+)\s+)?
- 一个可选的非捕获组,它将匹配 1 次或 0 次出现的 1+ 个非空白字符(捕获到组 1 中),然后匹配 1+ 个空白字符
({{.*?}})
- 第 2 组:{{
,除换行字符外的任何 0+ 个字符,尽可能少
(?=(?:\s+(\S+))?)
- 正向前瞻,需要在当前位置右侧紧接 1+ 个空白字符和 1+ 个非空白字符的可选序列,同时将非空白字符捕获到第 3 组中,但强制正则表达式索引保持在尝试匹配前瞻模式之前的位置,因为前瞻是零宽度断言。
示例字符串:
Hi,
{{name}} from {{place}} has closed your leave application (#2473)
此处正则表达式应全局匹配花括号前和下一个单词。
例如。
for {{name}} it should match hi and from.
for {{place}} it should match from and has.
我写的正则表达式:
/([^\ ]+?)? +?({{.+?}})[ \n]+([^\ {]+)?/iug
如果两个大括号之间有一个以上的词,这就是正确匹配。如果只有 1 个字词,则会导致问题。
目前,
for {{name}} it matches hi and from. -- this is correclty
for {{place}} it matches has. -- this is wrong, it should match from also
REGEX101link
样本原文
Hi,
Vinod Sai from hyderabad has closed your leave application (#2473)
您可以像这样将最后一部分包含在积极的前瞻中:
(?:(\S+)\s+)?({{.*?}})(?=(?:\s+(\S+))?)
详情
(?:(\S+)\s+)?
- 一个可选的非捕获组,它将匹配 1 次或 0 次出现的 1+ 个非空白字符(捕获到组 1 中),然后匹配 1+ 个空白字符({{.*?}})
- 第 2 组:{{
,除换行字符外的任何 0+ 个字符,尽可能少(?=(?:\s+(\S+))?)
- 正向前瞻,需要在当前位置右侧紧接 1+ 个空白字符和 1+ 个非空白字符的可选序列,同时将非空白字符捕获到第 3 组中,但强制正则表达式索引保持在尝试匹配前瞻模式之前的位置,因为前瞻是零宽度断言。