[英]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.