Ryg*_*014 3 javascript regex split replace input
所以目前,我的代码适用于包含一组括号的输入.
var re = /^.*\((.*\)).*$/;
var inPar = userIn.replace(re, '$1');
Run Code Online (Sandbox Code Playgroud)
...意思是当用户输入化学式Cu(NO3)2时,警告inPar返回NO3),这是我想要的.
但是,如果输入Cu(NO3)2(CO2)3,则仅返回CO2).
我在RegEx中不太了解,所以为什么会发生这种情况,有没有办法在发现NO3和CO2后将它们放入数组?
Spe*_*erJ 11
您想使用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)"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7982 次 |
| 最近记录: |