簡體   English   中英

JS Regex:在單引號之間匹配字符串中的單詞

[英]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'))

我只是騙你的RegexPal上的例子並想出以下表達式: '(.*)test(.*)'

這也有效

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM