Javascript - 正则表达式查找多个括号匹配

2024-01-31

因此,目前,我的代码适用于包含一组括号的输入。

var re = /^.*\((.*\)).*$/;
var inPar = userIn.replace(re, '$1');

...意味着当用户输入化学式 Cu(NO3)2 时,警报 inPar 返回 NO3) ,这是我想要的。

但是,如果输入 Cu(NO3)2(CO2)3,则仅返回 CO2)。

我对正则表达式不太了解,那么为什么会发生这种情况,有没有办法在找到它们后将 NO3) 和 CO2) 放入数组中?


你想使用字符串匹配 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match而不是 String.replace。您还希望正则表达式匹配括号中的多个字符串,因此不能有 ^ (字符串开头)和 $ (字符串结尾)。而且在括号内匹配时我们不能贪心,所以我们会使用.*?

逐步完成这些更改,我们得到:

// Use Match
"Cu(NO3)2(CO2)3".match(/^.*\((.*\)).*$/);
["Cu(NO3)2(CO2)3", "CO2)"]

// Lets stop including the ) in our match
"Cu(NO3)2(CO2)3".match(/^.*\((.*)\).*$/);
["Cu(NO3)2(CO2)3", "CO2"]

// Instead of matching the entire string, lets search for just what we want
"Cu(NO3)2(CO2)3".match(/\((.*)\)/);
["(NO3)2(CO2)", "NO3)2(CO2"]

// Oops, we're being a bit too greedy, and capturing everything in a single match
"Cu(NO3)2(CO2)3".match(/\((.*?)\)/);
["(NO3)", "NO3"]

// Looks like we're only searching for a single result. Lets add the Global flag
"Cu(NO3)2(CO2)3".match(/\((.*?)\)/g);
["(NO3)", "(CO2)"]

// Global captures the entire match, and ignore our capture groups, so lets remove them
"Cu(NO3)2(CO2)3".match(/\(.*?\)/g);
["(NO3)", "(CO2)"]

// Now to remove the parentheses. We can use Array.prototype.map for that!
var elements = "Cu(NO3)2(CO2)3".match(/\(.*?\)/g);
elements = elements.map(function(match) { return match.slice(1, -1); })
["NO3", "CO2"]

// And if you want the closing parenthesis as Fabrício Matté mentioned
var elements = "Cu(NO3)2(CO2)3".match(/\(.*?\)/g);
elements = elements.map(function(match) { return match.substr(1); })
["NO3)", "CO2)"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript - 正则表达式查找多个括号匹配 的相关文章

随机推荐