[英]Regex to match a string only inside another string
假設這里是一個示例文本:
Hello this is testing _testisgood _test test ilovetesting again test
正則表達式
/test/gi
提供所有test
,但我只想要被其他字符包圍的test
字符串,除了空格意味着與完全匹配相反。 換句話說,我想匹配的test
, _testisgood
, ilovetesting
中的testing
。
比爾的回答很好,但願你喜歡這個:只需找到所有帶有 test 的單詞,然后過濾掉無用的單詞;
const s = "Hello this is testing _testisgood _test test ilovetesting again test"
console.log(
(s.match(/[^\s]*test[^\s]*/gi) || []).filter(s => s !== 'test')
)
您可以通過在test
之前和之后指定一個或多個不是空格的字符來匹配示例中的_testisgood
和ilovetesting
,如下所示:
/[^\s]+test[^\s]+/gi
如果您還想匹配testing
,則從模式的開頭刪除[^\s]+
。
當下面的正則表達式具有非空格字符前綴或后修復它時,它將匹配'test'
。
/([^\s]+test[^\s]*|[^\s]*test[^\s]+)/gi;
const sentence = "Hello this is testing _testisgood _test test ilovetesting again test"; regex = /([^\s]+test[^\s]*|[^\s]*test[^\s]+)/gi; console.log(sentence.match(regex));
應該仍然像這樣工作\btest\w+|\w+test\b|\w+test\B\w+
由於您的場景中的“單詞”是一個或多個非空白字符的塊(並且非空白字符與正則表達式中的\S
匹配)您可以使用
console.log( "Hello this is testing _testisgood _test test ilovetesting again test".match(/\S+test\S*|\S*test\S+/gi)) // => ["testing","_testisgood", "_test", "ilovetesting"]
在這里, \S+test\S*|\S*test\S+
(見這個正則表達式演示)匹配
\S+test\S*
- 一個或多個非空白字符, test
和零個或多個非空白字符|
- 或者\S*test\S+
- 零個或多個非空白字符, test
和一個或多個非空白字符。 或者,您可以使用任何一個或多個空白字符(使用.split(/\s+/)
)進行拆分,然后過濾掉任何等於test
字符串或不包含test
字符串的塊:
console.log( "Hello this is testing _testisgood _test test ilovetesting again test".split(/\s+/).filter(x => x.toLowerCase().= "test" && x.toLowerCase().includes("test")))
考慮到您預期的 output ,您似乎想要匹配任何包含test
和至少一個字母的非空白塊。 在這種情況下,您可以使用
console.log( "Hello this is testing _testisgood _test test ilovetesting again test".match(/[^\sa-zA-Z]*[a-zA-Z]\S*test\S*|\S*test[^\sa-zA-Z]*[a-zA-Z]\S*/gi)) // => ["testing","_testisgood", "_test", "ilovetesting"]
請參閱此正則表達式演示。 Output: ["testing", "_testisgood", "ilovetesting"]
詳情:
[^\sa-zA-Z]*
- 除空格和字母之外的任何零個或多個字符[a-zA-Z]
- 一個字母\S*test\S*
- 用零個或多個非空白字符包圍的test
|
- 或者\S*test[^\sa-zA-Z]*[a-zA-Z]\S*
- 零個或多個非空白字符, test
,除空白和字母之外的任何零個或多個字符,然后是一個字母和零個或多個非空白字符。如果你想要的是:
提供所有測試,但我只想要被其他字符包圍的測試字符串
讓我們用另一種方法 string built-in functions來代替Regex
function surroundedBy(string, wordInMiddle){
const allWords = s.split(/\s+/);
const wordsSurrounded = allWords.filter(word=>word.toLowerCase().includes(wordInMiddle) &&
!word.startsWith(wordInMiddle) &&
!word.endsWith(wordInMiddle))
return wordsSurrounded;
}
測試:
const s = "Hello this is testing _testisgood _test test ilovetesting again test"
console.log(surroundedBy(s,'test'))
結果: ['_testisgood', 'ilovetesting']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.