3 回答

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以嘗試: /\([^\)]+\)/g
\(
: 轉(zhuǎn)義字符[^\)]+
: 一個(gè)或多個(gè)字符(包括符號)直到)
char。\)
: 轉(zhuǎn)義字符g
標(biāo)志:搜索所有巧合
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
);
尖端:
關(guān)于第 2 點(diǎn),您可以更改為
[\)]*
對零個(gè)或多個(gè)字符生效。
如果你只需要字符串,你可以使用
\w+
or\w*
。
如果你只需要的話,你可以使用
/\(\b\w+\b\)/g

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
除了使用組或match
結(jié)果的后處理之外,您還可以使用match
前瞻/后視的單個(gè)正則表達(dá)式:
var text = " (hello) world this is (hi) text"
var output = text.match(/(?<=\().*?(?=\))/g)
console.log(output)
輸出:
[?'hello',?'hi'?]
解釋:
(?<=...)
...積極回顧。匹配在 be 之前...
,但...
不包含在匹配中(?<=\()
... 正面回顧(
角色.*
...任何字符的零次或多次.*?
...的非貪婪版本.*
(?=...)
...積極的前瞻,比賽之后是...
但...
不包括在比賽中(?=\))
)
...角色的正面前瞻/.../g
...g
是全局標(biāo)志,匹配找到所有,而不僅僅是第一個(gè),出現(xiàn)不要忘記轉(zhuǎn)義“特殊字符”,例如括號

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
'(hello) world this is (hi) text'.match(/\([\w]*\)/g)
這將返回[ "(hello)", "(hi)" ],您可以運(yùn)行另一個(gè)解析函數(shù)來刪除那個(gè)額外的括號。
const text = '(hello) world this is (hi) text';
const list = text.match(/\([\w]*\)/g);
const parsed = list.map(item => item.replace(/\(|\)/g, ''));
console.log(parsed);
添加回答
舉報(bào)