3 回答

TA貢獻1858條經驗 獲得超8個贊
你可以嘗試: /\([^\)]+\)/g
\(
: 轉義字符[^\)]+
: 一個或多個字符(包括符號)直到)
char。\)
: 轉義字符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
);
尖端:
關于第 2 點,您可以更改為
[\)]*
對零個或多個字符生效。
如果你只需要字符串,你可以使用
\w+
or\w*
。
如果你只需要的話,你可以使用
/\(\b\w+\b\)/g

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

TA貢獻1895條經驗 獲得超7個贊
'(hello) world this is (hi) text'.match(/\([\w]*\)/g)
這將返回[ "(hello)", "(hi)" ],您可以運行另一個解析函數來刪除那個額外的括號。
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);
添加回答
舉報