[英]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.