gpt4 book ai didi

javascript - 使用正则表达式获取括号内的字符串,删除括号

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:35:39 27 4
gpt4 key购买 nike

我有这两个字符串...

var str1 = "this is (1) test";
var str2 = "this is (2) test";

并且想要编写一个 RegEx 来提取括号内的内容,如 "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);

jsfiddle

参见 MDN RegExp

(x) Matches x and remembers the match. These are called capturing parentheses.

For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements 1, ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

关于javascript - 使用正则表达式获取括号内的字符串,删除括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18559762/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com