简体   繁体   English

匹配正确字符串的确切正则表达式是什么?

[英]What's the exact regex to match the proper string?

My string has [1212,1212],[1212,11212],... 我的字符串有[1212,1212],[1212,11212],...

I'd like to extract each value into an array for example I'd want 1212,1212 as one pair and evaluate a series of steps. 我想将每个值提取到一个数组中,例如,我想将1212,1212作为一对并评估一系列步骤。

Tried /[[0-9],[0-9]]/ but It wasn't doing the task as I wanted. 试过/[[0-9],[0-9]]/但是没有执行我想要的任务。 Basically I'm a noob in Regex, could someone please help. 基本上我是Regex的菜鸟,请有人帮忙。

Thanks in advance 提前致谢

You need some modifications for your regular expression for it to work correctly: 您需要对正则表达式进行一些修改才能使其正常工作:

/\[[0-9]+,[0-9]+\]/g
  1. You need to escape square brackets [ because they have special meaning. 您需要转义方括号[因为它们具有特殊含义。
  2. [0-9] matches only one digits, you need the + quantifier to match one or more digits and thus [0-9]+ . [0-9]仅匹配一位数字,您需要+量词以匹配一位或多位数字,因此需要[0-9]+
  3. Use the global modifier g to extract all matches. 使用全局修饰符g提取所有匹配项。

Then you can extract all the values into an array like this: 然后,您可以将所有值提取到数组中,如下所示:

var input = "[1212,1212],[1212,11212]";
var pattern = /\[[0-9]+,[0-9]+\]/g;
var result = [];
var currentMatch;
while((currentMatch = pattern.exec(input)) != null) {
    result.push(currentMatch.toString());
}
result;

Or if you don't need to find the matches successively one at a time, then you can use String.match() as @Matthew Mcveigh did: 或者,如果您不需要一次连续找到匹配项,则可以像@Matthew Mcveigh一样使用String.match()

var input = "[1212,1212],[1212,11212]";
var result = input.match(/\[[0-9]+,[0-9]+\]/g);

You need to escape the literal brackets that you want to match. 您需要转义要匹配的文字括号。 You can also use \\d to match "any digit", which makes it tidier. 您也可以使用\\d匹配“任意数字”,从而使其更整齐。 Also, you're only matching one digit. 另外,您只匹配一位数字。 You need to match "one or more" ( + quantifier) 您需要匹配“一个或多个”( +量词)

/\[\d+,\d+\]/g

That g modifier finds all matches in the string, otherwise only the first one is found. g修饰符会找到字符串中的所有匹配项,否则只会找到第一个。

It seems like you just need to match one or more digits before and after a comma, so you could do the following: 看来您只需要在逗号前后匹配一位或多位数字,就可以执行以下操作:

"[1212,1212],[1212,11212]".match(/\d+,\d+/g)

Which will give you the array: ["1212,1212", "1212,11212"] 这将为您提供数组: ["1212,1212", "1212,11212"]

To extract the pairs: 要提取对:

var result = "[1212,1212],[1212,11212]".match(/\d+,\d+/g);

for (var i = 0; i < result.length; i++) {
    var pair = result[i].match(/\d+/g),
        left = pair[0], right = pair[1];

    alert("left: " + left + ", right: " + right);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM