Javascript 获取两个圆括号之间的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12059284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get text between two rounded brackets
提问by Vikas
How can I retrieve the word my
from between the two rounded brackets in the following sentence using a regex in JavaScript?
如何my
使用 JavaScript 中的正则表达式从以下句子中的两个圆括号之间检索单词?
"This is (my) simple text"
“这是(我的)简单文本”
回答by Michael Krelin - hacker
console.log(
"This is (my) simple text".match(/\(([^)]+)\)/)[1]
);
\(
being opening brace, (
—?start of subexpression, [^)]+
—?anything but closing parenthesis one or more times (you may want to replace +
with *
), )
—?end of subexpression, \)
— closing brace. The match()
returns an array ["(my)","my"]
from which the second element is extracted.
\(
是开括号,(
-启动子表达式,[^)]+
- ?任何事情,但右括号一次或多次(你可能需要更换+
同*
),)
- ?子表达式的结束,\)
-右大括号。该match()
返回的数组["(my)","my"]
从中提取第二元件。
回答by j08691
var txt = "This is (my) simple text";
re = /\((.*)\)/;
console.log(txt.match(re)[1]);?
回答by SexyBeast
You may also try a non-regex method (of course if there are multiple such brackets, it will eventually need looping, or regex)
你也可以尝试一个非正则表达式的方法(当然如果有多个这样的括号,它最终会需要循环,或者正则表达式)
init = txt.indexOf('(');
fin = txt.indexOf(')');
console.log(txt.substr(init+1,fin-init-1))
回答by Yu Mai Lin
For anyone looking to return multiple texts in multiple brackets
对于希望在多个括号中返回多个文本的任何人
var testString = "(Charles) de (Gaulle), (Paris) [CDG]"
var reBrackets = /\((.*?)\)/g;
var listOfText = [];
var found;
while(found = reBrackets.exec(testString)) {
listOfText.push(found[1]);
};