簡體   English   中英

如何使用正則表達式搜索帶括號的字符串

[英]How to search strings with brackets using Regular expressions

我有一種情況,我想搜索數組中的所有Hello (World) 您好(世界)來自變量,並且可以更改。 我想使用RegExp而不是indexOfincludes方法來實現這一點。

testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)']

我的比賽應返回索引1和2作為答案。

轉義字符串( 此答案中的算法)后,請使用RegExp構造函數,並使用一些數組方法:

 const testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)']; const string = "Hello (World)".replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); const regex = new RegExp(string, "i"); const indexes = testArray.map((e, i) => e.match(regex) == null ? null : i).filter(e => e != null); console.log(indexes); 

此表達式可以幫助您做到這一點:

(\w+)\s\((\w+)

您可能不需要從左到右綁定它,因為您的輸入字符串結構良好。 您可能只關注您想要的捕獲組,我假設這些捕獲組是一個單詞,您可以對其進行簡單地修改。

使用簡單的字符串替換,您可以匹配並捕獲它們兩者。

在此處輸入圖片說明

RegEx描述圖

此圖顯示了表達式的工作方式,您可以在此鏈接中可視化其他表達式:

在此處輸入圖片說明

性能測試

該JavaScript代碼段使用了簡單的100萬次for循環來顯示該表達式的性能。

 repeat = 1000000; start = Date.now(); for (var i = repeat; i >= 0; i--) { var string = "Hello (World"; var regex = /(\\w+)\\s\\((\\w+)/g; var match = string.replace(regex, "$1 & $2"); } end = Date.now() - start; console.log("YAAAY! \\"" + match + "\\" is a match 💚💚💚 "); console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 "); 

 testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)']; let indexes = []; testArray.map((word,i)=>{ if(word.match(/\\(.*\\)/)){ indexes.push(i); } }); console.log(indexes); 

暫無
暫無

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

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