简体   繁体   English

Javascript正则表达式可以匹配两个字符串之间的子字符串,但是子字符串可以包含DOT(。)

[英]Javascript Regex to match substrings between two Strings but the substrings can contain DOT (.)

I do want to match all subbstrings which are between {{ and }} 我确实想匹配{{}}之间的所有子字符串

When this substring does not contain . 当此子字符串不包含时. , the regex works fine : ,正则表达式可以正常工作:

"When he come, {{person}} will give his son {{something}}".match(/{{(\w*)}}/g) ; 

Result : 结果:

["{{person}}", "{{something}}"] [“ {{person}}”,“ {{something}}”]]

Now , if this substring contains . 现在,如果此子字符串包含. (dot) , the regex does not work as it is expected : (点),正则表达式无法正常运行:

"When he come, {{person.firstname}} will give his son {{something}}".match(/{{(\w*)}}/g) ;

Result : 结果:

["{{something}}"] [ “{{事}}”]

How to change the regex to be able to mach also substrings contains DOT , for example here : person.firstname . 如何更改正则表达式以也可以处理包含DOT的子字符串,例如: person.firstname ?

or use this pattern to match anything between {{ and }} 或使用此模式来匹配{{}}之间的任何内容

{{([^}]*)}}

explanation: 说明:

[^}] a character class, anything but "}"

\\w will only match az, AZ, 0-9, _ , cf. \\w仅匹配az, AZ, 0-9, _和cf。 http://www.w3schools.com/jsref/jsref_regexp_wordchar.asp . http://www.w3schools.com/jsref/jsref_regexp_wordchar.asp

Use this regular expression to include an arbitrary number of points as well: 使用此正则表达式还可以包含任意数量的点:

/{{([\w\.]*)}}/g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM