I need to extract the number from the following simple string:
base:873
where the “base:” portion is optional, i.e., it may/may not exist in the string.
How am I supposed to extract the number from the above string using RegExp?
P.S.: It’s an unfortunate to see such a big difference between other Regular Expression implementation and the JavaScript’s one.
TIA,
Mehdi
UPDATE1:
Consider this loop:
for (var i = 0; i < 3; i++) {
code = '216';
var matches = /(bid:)?(\d+)/ig.exec(code);
if (matches != null) {
console.log('>>>' + matches[0]);
}
else {
console.log('>>> no match');
}
}
Please note that the “code” variable is set within the loop, just for testing purposes only. However, the amazing thing is that the above mentioned code prints this:
>>>216
>>> no match
>>>216
How this could be possible???
Well, if the
base:is optional, you don’t need to care about it, do you?is all you need.
will return the (first) number in the string
subject.Or did you mean: Match the number only if it is either the only thing in the string, or if it is preceded by
base:?In this case, use
^(?:base:)?(\d+)$.