Ovilia
Ovilia

Reputation: 7310

JavaScript Regular Expression last match

To search in the string a='c761uc762uc201tc202t' and get the closest number before 1t.

Expect to get 20, but with a.match(/(c*){2,}(.*?)1t/), I get ["c761uc762uc201t", "", "761uc762uc20"].

a may be like c*1uc*2uc*1tc*2t or c*1uc*1t. If a is "c761uc201t", also expect to get "20" in this case.

Any hint how should I write the regular expression to get 20?

Upvotes: 2

Views: 54

Answers (2)

Ismael Miguel
Ismael Miguel

Reputation: 4241

This is my go on this question:

/(\d{2})\dt$/

This will fetch the number before any <number>t at the end of the string.

>>> 'c761uc762uc201tc202t'.match(/(\d{2})\dt$/);
Array ["202t", "20"]
>>> 'c761uc201t'.match(/(\d{2})\dt$/);
Array ["201t", "20"]

This was the shortest answer I could come up with.

If you want only the one after 1t, try this:

/(\d{2})1t/

This works like this:

>>> 'c761uc762uc201tc202t'.match(/(\d{2})1t/);
Array ["201t", "20"]
>>> 'c761uc201t'.match(/(\d{2})1t/);
Array ["201t", "20"]

Upvotes: 2

anubhava
anubhava

Reputation: 786289

You can use:

var r = a.match(/^(?:[^c]*c){1,3}(.*)1t/)[1];
// 20

Or to make it safer:

var r = (a.match(/^(?:[^c]*c){1,3}(.*)1t/) || [null, null])[1];
// 20

a='c*1uc*2uc*1tc*2t';
var r = (a.match(/^(?:[^c]*c){1,3}(.*)1t/) || [null, null])[1];
// *

a='c*1uc*1t'
r = (a.match(/^(?:[^c]*c){1,3}(.*)1t/) || [null, null])[1]
// null

a="c761uc201t";
r = (a.match(/^(?:[^c]*c){1,3}(.*)1t/) || [null, null])[1]
// 20

Upvotes: 1

Related Questions