正则表达式找到多个括号匹配

正则表达式找到多个括号匹配

本文介绍了Javascript - 正则表达式找到多个括号匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So currently, my code works for inputs that contain one set of parentheses.

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

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

...meaning when the user enters the chemical formula Cu(NO3)2, alerting inPar returns NO3) , which I want.

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

However, if Cu(NO3)2(CO2)3 is the input, only CO2) is being returned.

我在RegEx中不太了解,所以为什么会发生这种情况,有没有办法在发现它们后将NO3和CO2)放入数组?

I'm not too knowledgable in RegEx, so why is this happening, and is there a way I could put NO3) and CO2) into an array after they are found?

推荐答案

您想使用而不是String.replace。您还希望正则表达式匹配括号中的多个字符串,因此您不能拥有^(字符串的开头)和$(字符串的结尾)。在括号内匹配时我们不能贪婪,所以我们将使用。*?

You want to use String.match instead of String.replace. You'll also want your regex to match multiple strings in parentheses, so you can't have ^ (start of string) and $ (end of string). And we can't be greedy when matching inside the parentheses, so we'll use .*?

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

Stepping through the changes, we get:

// 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)"]

这篇关于Javascript - 正则表达式找到多个括号匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 11:10