Mottie
Mottie

Reputation: 86413

Help with regexp to extract values from inside brackets

I would like to get a regexp that will extract out the following. I have a regexp to validate it (I pieced it together, so it may not be the the best or most efficient).

some.text_here:[12,34],[56,78]

The portion before the colon can include a period or underline. The bracketed numbers after the colon are coordinates [x1,y1],[x2,y2]... I only need the numbers from here.

And here is the regexp validator I was using (for javascript):

^[\w\d\-\_\.]*:(\[\d+,\d+],\[\d+,\d+])

I'm fairly new to regexp but I can't figure out how to extract the values so I can get

name = "some.text_here"
x1 = 12
y1 = 34
x2 = 56
y2 = 78

Thanks for any help!

Upvotes: 2

Views: 1414

Answers (3)

Gumbo
Gumbo

Reputation: 655239

Try this regular expression:

/^([\w\d-_.]*):\[(\d+),(\d+)],\[(\d+),(\d+)]/

var str = "some.text_here:[12,34],[56,78]";
var match = str.match(/^([\w\d-_.]*):\[(\d+),(\d+)],\[(\d+),(\d+)]/);
alert("name = " + match[1] + "\n" + 
      "x1 = " + match[2] + "\n" +
      "x2 = " + match[3] + "\n" +
      "y1 = " + match[4] + "\n" +
      "y2 = " + match[5]);

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827406

You can use the match method of string:

var input = "some.text_here:[12,34],[56,78]";

var matches = input.match(/(.*):\[(\d+),(\d+)\],\[(\d+),(\d+)\]/);

var output = {
  name: matches[1],
  x1: matches[2],
  y1: matches[3],
  x2: matches[4],
  y2: matches[5]
}

// Object name=some.text_here x1=12 y1=34 x2=56 y2=78

Upvotes: 3

Kitson
Kitson

Reputation: 1678

You want something like:

/^(\S+):\[(\d+),(\d+)\],\[(\d+),(\d+)\]/

I am not sure if JavaScript supports the naming of caputre groups, but if it did, you could add those in as well.

Upvotes: 1

Related Questions