views:

359

answers:

3

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!

+1  A: 

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.

Kitson
+1  A: 

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]);
Gumbo
Thank you Gumbo, this works great... but I still needed the name extracted out. I was able to use CMS's regex in place of yours and it made match[1] contain the name. Thanks!
fudgey
Ah, I forgot that. Fixed it.
Gumbo
+2  A: 

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
CMS
Thanks CMS this works great!
fudgey