ACs
ACs

Reputation: 1445

capture with regex in javascript

I have a string like "ListUI_col_order[01234567][5]". I'd like to capture the two numeric sequences from the string. The last part between the square brackets may contain 2 digits, while the first numeric sequence always contains 8 digits (And the numbers are dynamically changing of course.) Im doing this in javascript and the code for the first part is simple: I get the only 8digit sequence from the string:

var str = $(this).attr('id');
var unique = str.match(/([0-9]){8}/g);

Getting the second part is a bit complicated to me. I cannot simply use:

var column = str.match(/[0-9]{1,2}/g)

Because this will match '01', '23', '45', '67', '5' in our example, It's clear. Although I'm able to get the information what I need as column[4], because the first part always contains 8 digits, but I'd like a nicer way to retrieve the last number. So I define the contex and I can tell the regex that Im looking for a 1 or 2 digit number which has square brackets directly before and after it:

var column = str.match(/\[[0-9]{1,2}\]/g)
// this will return [5]. which is nearly what I want

So to get Only the numeric data I use parenthesis to capture only the numbers like:

 var column = str.match(/\[([0-9]){1,2}\]/g)
 // this will result in:
 // column[0] = '[5]'
 // column[1] = [5]

So my question is how to match the '[5]' but only capture the '5'? I have only the [0-9] between the parenthesis, but this will still capture the square brackets as well

Upvotes: 2

Views: 135

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

Unfortunately, JavaScript does not support the lookbehind necessary to do this. In other languages such as PHP, it'd be as simple as /(?<=\[)\d{1,2}(?=\])/, but in JavaScript I am not aware of any way to do this other than use a capturing subpattern as you are here, and getting that index from the result array.

Side-note, it's usually better to put the quantifier inside the capturing group - otherwise you're repeating the group itself, not its contents!

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382514

You can get both numbers in one go :

var m = str.match(/\[(\d{8})\]\[(\d{1,2})\]$/)

For your example, this makes ["[01234567][5]", "01234567", "5"]

To get both matches as numbers, you can then do

if (m) return m.slice(1).map(Number)

which builds [1234567, 5]

Upvotes: 2

Related Questions