我有文字
var text = (hello) world this is (hi) text
我想编写一个正则表达式函数,这样我就可以得到
parseText(text) // returns ['hello', 'hi']
我尝试过这个但不起作用:
'(hello) world this is (hi) text'.match('((.*?))')
感谢您的帮助
最佳答案
你可以尝试:
/\([^\)]+\)/g
\(
:转义字符[^\)]+
:一个或多个字符(包括符号)直到)
个字符。\)
:转义字符g
标志:搜索所有巧合
const regex = /\([^\)]+\)/g;
const str = `(hello) world this is (hi) text`;
console.log(
str.match(regex) // this returns an string array
.map(i => i.slice(1, -1)) // remove first and last char
);
提示:
About point #2, you can change to
[\)]*
to take effect over zero or more character.
If you need only string, you can use
\w+
or\w*
.
If you need only words you can use
/\(\b\w+\b\)/g
关于javascript - 正则表达式获取 () 之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63993059/