简体   繁体   中英

What's the exact regex to match the proper string?

My string has [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.

Tried /[[0-9],[0-9]]/ but It wasn't doing the task as I wanted. Basically I'm a noob in Regex, could someone please help.

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]+ .
  3. Use the global modifier g to extract all matches.

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:

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. 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.

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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