I need to extract the number from the following simple string:
base:873
where the "base:" portion is optional, ie, it may/may not exist in the string.
How am I supposed to extract the number from the above string using RegExp?
PS: 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?
\d+
is all you need.
result = subject.match(/\d+/);
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+)$
.
var match = /^(?:base:)?(\d+)$/.exec(subject);
if (match != null) {
result = match[1];
}
Try (base:)?(\\d+)
The number will be in the second capture variable.
Alternately, replace "base:" with nothing.
Or split on the ':'.
Or whatever.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.