Mic*_*ker 77
console.log(
"This is (my) simple text".match(/\(([^)]+)\)/)[1]
);
Run Code Online (Sandbox Code Playgroud)
\(
是左括号,(
-子表达式的开始,[^)]+
-什么,但右括号一次或多次(你可能需要更换+
同*
),)
-子表达式的结束,\)
-右大括号.该match()
返回的数组["(my)","my"]
从中提取第二元件.
j08*_*691 14
var txt = "This is (my) simple text";
re = /\((.*)\)/;
console.log(txt.match(re)[1]);?
Run Code Online (Sandbox Code Playgroud)
您也可以尝试非正则表达式方法(当然,如果有多个这样的括号,它最终将需要循环或正则表达式)
init = txt.indexOf('(');
fin = txt.indexOf(')');
console.log(txt.substr(init+1,fin-init-1))
Run Code Online (Sandbox Code Playgroud)
使用它来获取最接近的(
和之间的文本)
:
const string = "This is (my) (simple (text)"
console.log( string.match(/\(([^()]*)\)/)[1] )
console.log( string.match(/\(([^()]*)\)/g).map(function($0) { return $0.substring(1,$0.length-1) }) )
Run Code Online (Sandbox Code Playgroud)
结果:my
和["my","text"]
。
解释
--------------------------------------------------------------------------------
\( '('
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^()]* any character except: '(', ')' (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\) ')'
Run Code Online (Sandbox Code Playgroud)
小智 5
对于希望在多个括号中返回多个文本的任何人
var testString = "(Charles) de (Gaulle), (Paris) [CDG]"
var reBrackets = /\((.*?)\)/g;
var listOfText = [];
var found;
while(found = reBrackets.exec(testString)) {
listOfText.push(found[1]);
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
52234 次 |
最近记录: |