[英]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 . 对于{{name}},它应与hi和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. 如果两个curley支撑项之间的词不止一个,则这是正确匹配的。 If there is only 1 word it is causing issue. 如果只有1个字,则会引起问题。
Currently, 目前,
for {{name}} it matches hi and from . 对于{{name}},它与hi和from匹配。 -- this is correclty -这是正确的
for {{place}} it matches has . 匹配的{{place}} 拥有 。 -- this is wrong, it should match from also -这是错误的,它应该也匹配
REGEX101 link REGEX101链接
https://regex101.com/r/wtyOIB/1 https://regex101.com/r/wtyOIB/1
The original text for sample 样本原始文本
Hi,
Vinod Sai from hyderabad has closed your leave application (#2473)
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 -一个可选的非捕获组,它将匹配1个或0个出现的1+个非空白字符(捕获到第1组),然后匹配1+个空白字符 ({{.*?}})
- Group 2: {{
, any 0+ chars other than line break chars, as few as possible ({{.*?}})
-组2: {{
,除换行符外的任何0+个字符,尽可能少 (?=(?:\\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. (?=(?:\\s+(\\S+))?)
-正向超前,需要立即在当前位置的右侧添加一个可选的1+个空白字符和1+个非空白字符的序列,同时捕获非-空格将字符归为第3组,但由于正则行头是零宽度的断言,因此会迫使正则表达式索引保持在尝试匹配先行模式之前的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.