我需要从多组括号中获取多个文本,如果不超过一组,那么我只需要从那一组括号中获取文本。
1)示例:
My sentence is :
A Cef (1000mg) (Sterlie Ceftriaxone) Price List.
现在,我需要得到这样的输出:
Output :
1000mg Sterlie Ceftriaxone
2)如果我只有这样的单一套装:Aamin A(阿替洛尔)价格表。
然后我的输出应该是:Atenolol
我正在使用这个javascript代码:
function myFunction() {
var str = "A Cef (1000mg) (Sterlie Ceftriaxone) Price List.";
var res = str.match(/\((.*))\)/);
document.getElementById("demo").innerHTML = res[1];
}
第二种情况完全正常,但当我将它用于第一种情况时,它会给我这个输出。
Output :1000mg) (Sterlie Ceftriaxone
答案 0 :(得分:2)
使用非贪婪的表达式/\((.+?)\)/gm
。
见https://regex101.com/r/OKvbXy/1
function myFunction(text) {
var res = text.match(/\((.+?)\)/g);
var cleanedUp = res.join(' ').replace(/[()]/g,''); // remove () and join matches
console.log( cleanedUp );
}
myFunction("A Cef (1000mg) (Sterlie Ceftriaxone) Price List.");
myFunction("Aamin A (Atenolol) Price List.");
顺便说一下,你的代码与jQuery无关(你甚至没有在你的代码中使用它)
答案 1 :(得分:1)
这是因为*是greedy。您还希望进行global匹配以获得所有结果。
试试这个 -
Button b = new Button {Text = "This is the focused button"};
b.Focus();
答案 2 :(得分:0)
我相信问题是通过使用.*
(通配符),您将捕获括号和空格。
如果您改用var res = str.match(/\(([0-9a-zA-Z]+)\)/);
,它将捕获第一个组,因为它与示例中的括号或空格不匹配。