最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS Regex: Match word in a string between single quotes - Stack Overflow

programmeradmin2浏览0评论

I'm trying to figure out a regex which yields any string between single quotes ('), IF that string contains a given word.

For example, assume I have the following text, and I want to match everything between single quotes that contains the word "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.

The regex would need to return two matches, namely

"this is a test match"
"this is a match again because it contains the word test"

I'm a bit lost here. I tried text.match( /'(.*?)'/); to return everything between single quotes, and then subsequently have a function check for a substring match. But oddly that regex didn't even seem to return all strings within single quotes property.

Would greatly appreciate a pointer.. thanks!

I'm trying to figure out a regex which yields any string between single quotes ('), IF that string contains a given word.

For example, assume I have the following text, and I want to match everything between single quotes that contains the word "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.

The regex would need to return two matches, namely

"this is a test match"
"this is a match again because it contains the word test"

I'm a bit lost here. I tried text.match( /'(.*?)'/); to return everything between single quotes, and then subsequently have a function check for a substring match. But oddly that regex didn't even seem to return all strings within single quotes property.

Would greatly appreciate a pointer.. thanks!

Share Improve this question asked Aug 30, 2015 at 13:13 BogeyBogey 5,7444 gold badges34 silver badges73 bronze badges 1
  • please format your inline code correctly like so: `code` – Daniel Cheung Commented Aug 30, 2015 at 13:25
Add a ment  | 

3 Answers 3

Reset to default 9

Your regex is correct except you want to match all occurance so use g for global search for all matches:

 text.match(/'(.*?)'/g)

and to match for exact word:

 text.match(/'(.*?test.*?)'/g)

You can allow it to be generic for any word by formulate the Regualr Expression using:

word = 'test'
text.match(RegExp("'(.*?"+word+".*?)'", 'g'))

I just fooled around with your example on RegexPal and figured out following expression: '(.*)test(.*)'

This also works

/\'.*(test).*\'/g

https://regex101./r/bD6zF0/1

发布评论

评论列表(0)

  1. 暂无评论