views:

55

answers:

2

Hi, 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???

A: 

Try (base:)?(\d+)

The number will be in the second capture variable.

Alternately, replace "base:" with nothing.

Or split on the ':'.

Or whatever.

Borealid
+3  A: 

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];
}
Tim Pietzcker
You don't even need the capturing group, e.g. `'base:873'.match(/\d+/)[0];` :)
CMS
Right! Let's make this even simpler! Thanks :)
Tim Pietzcker
Well, thanks. However, I've updated the question. Would you please consider the update?
Mehdi
You should really be checking for `null` using `!==`.
strager
@strager: I must admit that I don't know JavaScript; the above is a code snippet from RegexBuddy. What's the problem with `!=`?
Tim Pietzcker
@Tim, @strager: There is no problem with `!=` in this case, because the `exec` method [is guaranteed](http://bclary.com/2004/11/07/#a-15.10.6.2) to return either an Array object or `null`. The fear about the non-strict equality operators (started by Doug. Crockford and his JSLint) is about the non-transitive properties of those operators and having false positive. In this case when comparing against `null` the only possible value that could do a false positive is `undefined` since `null == undefined` but the `exec` method will **never** return `undefined`... [See also](http://j.mp/c5Yyz1).
CMS