[英]JS Regex: Match word in a string between single quotes
我试图找出一个正则表达式,它产生单引号(')之间的任何字符串,如果该字符串包含给定的单词。
例如,假设我有以下文本,并且我希望匹配包含单词“test”的单引号之间的所有内容:
Some sample text,
'this is test a match' and
'this is not a match' but
'this is a match again because it contains the word test'.
This "is not a test match because its double quotes".
And this is not a test match either because this is not encapsulated in quotes.
正则表达式需要返回两个匹配,即
"this is a test match"
"this is a match again because it contains the word test"
我在这里有点失落。 我试过text.match(/'(.*?)'/); 返回单引号之间的所有内容,然后对子字符串匹配进行函数检查。 但奇怪的是,正则表达式似乎甚至没有返回单引号属性中的所有字符串。
非常感谢指针..谢谢!
你的正则表达式是正确的,除非你想匹配所有出现,所以使用g
进行全局搜索所有匹配:
text.match(/'(.*?)'/g)
并匹配确切的单词:
text.match(/'(.*?test.*?)'/g)
您可以通过以下方式制定Regualr Expression来允许它对任何单词都是通用的:
word = 'test'
text.match(RegExp("'(.*?"+word+".*?)'", 'g'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.