[英]How to search strings with brackets using Regular expressions
我有一種情況,我想搜索數組中的所有Hello (World)
。 您好(世界)來自變量,並且可以更改。 我想使用RegExp而不是indexOf
或includes
方法來實現這一點。
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+)
您可能不需要從左到右綁定它,因為您的輸入字符串結構良好。 您可能只關注您想要的捕獲組,我假設這些捕獲組是一個單詞,您可以對其進行簡單地修改。
使用簡單的字符串替換,您可以匹配並捕獲它們兩者。
此圖顯示了表達式的工作方式,您可以在此鏈接中可視化其他表達式:
該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.