admin管理员组

文章数量:1425738

I have this string:

"irrelevant(AB:1;CD:2;EF:3)"

and I need to find a way to extract the AB, CD and EF values (1, 2 and 3 in the example) either as individual variables or as an array, using only JS functions.

The irrelevant part may have ( ) : and ; but the (AB:1;CD:2;EF:3) part is always at the end. The values are always numeric, of variable length, and the labels are always 2 uppercase letters.

Thanks for any assistance.

I have this string:

"irrelevant(AB:1;CD:2;EF:3)"

and I need to find a way to extract the AB, CD and EF values (1, 2 and 3 in the example) either as individual variables or as an array, using only JS functions.

The irrelevant part may have ( ) : and ; but the (AB:1;CD:2;EF:3) part is always at the end. The values are always numeric, of variable length, and the labels are always 2 uppercase letters.

Thanks for any assistance.

Share Improve this question edited Jul 20, 2012 at 0:52 Derek 朕會功夫 94.5k45 gold badges198 silver badges253 bronze badges asked Jun 2, 2012 at 20:16 HenryHenry 1,4342 gold badges15 silver badges25 bronze badges 6
  • 8 It sounds like you are asking someone to write a regular expression for you. What do you have so far? – Jeanne Boyarsky Commented Jun 2, 2012 at 20:18
  • Try yourself. anyway, examples of strings are needed. – gdoron Commented Jun 2, 2012 at 20:25
  • The easiest one is: str.split(/[^0-9]*/). It returns array of these values. – therealszaka Commented Jun 2, 2012 at 20:31
  • I had been trying along the lines of "irrelevant(AB:1;CD:2;EF:3)".match(/[AZ][AZ]*/g) without success. Dupadupa suggestion does the trick. Thanks! – Henry Commented Jun 2, 2012 at 20:37
  • 1 Change ( to ({ and ) to }) and ; to , and you have JSON – mplungjan Commented Jun 2, 2012 at 21:42
 |  Show 1 more ment

1 Answer 1

Reset to default 3

Try this code:

var txt = "irrelevant(AB:1;CD:2;EF:3)";
var m = txt.match(/(?:([A-Z]{1,}))\:([0-9]{1,})/gi);
var str = "";
for (var i = 0; i < m.length; i++) {
    var p = m[i].split (":");
    str += "Letters: " + p[0] + " - Number: " + p[1] + "\n";
}
​alert (str)​;

Look at this example in action Demo

Regards, Victor

本文标签: extract data by regex in javascriptStack Overflow