[英]Get string inside parentheses, removing parentheses, with regex
我有這兩個字符串......
var str1 = "this is (1) test";
var str2 = "this is (2) test";
並且想要編寫一個RegEx來提取INSIDE括號中的內容,如"1"
和"2"
以生成如下所示的字符串。
var str3 = "12";
現在我有這個正則表達式也返回括號...
var re = (/\((.*?)\)/g);
var str1 = str1.match(/\((.*?)\)/g);
var str2 = str2.match(/\((.*?)\)/g);
var str3 = str1+str2; //produces "(1)(2)"
像這樣
使用Javascript
var str1 = "this is (1) test",
str2 = "this is (2) test",
str3 = str1.match(/\((.*?)\)/)[1] + str2.match(/\((.*?)\)/)[1];
alert(str3);
請參閱MDN RegExp
(x)匹配x並記住匹配。 這些被稱為捕獲括號。
例如,/(foo)/匹配並記住“foo bar”中的'foo'。 可以從結果數組的元素1 ,...,[n]或預定義的RegExp對象的屬性$ 1,...,$ 9中調用匹配的子字符串。
捕獲組會降低性能。 如果您不需要調用匹配的子字符串,則更喜歡非捕獲括號(參見下文)。
嘗試:
/[a-zA-Z0-9\s]+\((\d+)\)[a-zA-Z0-9\s]+/
這將捕獲括號內的一個或多個數字。
示例: http : //regexr.com?365uj
編輯:在示例中,您將看到替換字段只有數字,而不是括號 - 這是因為捕獲組$1
僅捕獲數字本身。
編輯2:
嘗試這樣的事情:
var str1 = "this is (1) test";
var str2 = "this is (2) test";
var re = /[a-zA-Z0-9\s]+\((\d+)\)[a-zA-Z0-9\s]+/;
str1 = str1.replace(re, "$1");
str2 = str2.replace(re, "$1");
console.log(str1, str2);
試試這個
var re = (/\((.*?)\)/g);
var str1 = str1.match(/\((.*?)\)/g);
var new_str1=str1.substr(1,str1.length-1);
var str2 = str2.match(/\((.*?)\)/g);
var new_str2=str2.substr(1,str2.length-1);
var str3 = new_str1+new_str2; //produces "12"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.