1

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

2 Answers 2

3

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];
}
Sign up to request clarification or add additional context in comments.

6 Comments

You don't even need the capturing group, e.g. 'base:873'.match(/\d+/)[0]; :)
Right! Let's make this even simpler! Thanks :)
Well, thanks. However, I've updated the question. Would you please consider the update?
You should really be checking for null using !==.
@strager: I must admit that I don't know JavaScript; the above is a code snippet from RegexBuddy. What's the problem with !=?
|
0

Try (base:)?(\d+)

The number will be in the second capture variable.

Alternately, replace "base:" with nothing.

Or split on the ':'.

Or whatever.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.