ReneFroger
ReneFroger

Reputation: 530

What is the regex for matching any numbers, with spaces between them?

I searched and tried all possible regex solutions, but I couldn't find any answer. I'm looking for a regex, which matches the numbers with any spaces between them.

For example, the following senctences:

12 Voorbeeld3 4Voorbeeld5 6 test 777

Example1 2 33 4test

So the regex would match only 12, 6 and 777 in the first sentence and only 2 and 33 in the second sentence. So every digit(s) numbers which are between the spaces.

I tried the regex to looking for the whitespaces. For example, the (?<!\s[\d+]) But it match's only the single digits, and not multiple digits.

Any suggestions?

Thanks in advance.

Upvotes: 3

Views: 9509

Answers (5)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You need whitespace boundaries here:

(?<!\S)\d+(?!\S)

Details

  • (?<!\S) - left-hand whitespace boundary
  • \d+ - one or more digits
  • (?!\S) - right-hand whitespace boundary

See the regex demo.

Why not (?<=\s)\d+(?=\s)? Because this pattern requires at least one whitespace on each side of the digit sequence. The whitespace boundaries in this solution also allow matching at the start and end of the string.

Why not \b word boundaries? Because the question is about matching numbers that have whitespace as boundaries, and \b\d+\b also matches 1 in a#1#b`.

Upvotes: 1

Marco Bonelli
Marco Bonelli

Reputation: 69367

The RegExp you're looking for is the following:

\b(\d+)\b

The above RegExp will match any number between two word boundaries, and, therefore, it will match:

  • "123 "
  • " 123"
  • " 123 "

Use the g modifier to match all the occurrences (all the numbers). You can find a working example HERE.

JavaScript example:

var text = "12 Voorbeeld3 4Voorbeeld5 6 test 777",
    exp = /\b(\d+)\b/g,
    match;

while (match = exp.exec(text)) {
    console.log(match[0]);
}

Result:

12
6
777

Upvotes: 7

npinti
npinti

Reputation: 52185

You could use something like so: \b(\d+)\b. This will check to see if you have one or more digits surrounded by spaces. A sample of the regular expression can be seen here.

Upvotes: 1

eumiro
eumiro

Reputation: 213005

Groups of digits surrounded by whitespace (or at the beginning/end of string) can be matched using word boundaries:

\b\d+\b

Upvotes: 2

anubhava
anubhava

Reputation: 785611

You can use lookarounds:

(?<=\s)\d+(?=\s)

Or if lookarounds are not available then use captured groups:

\s(\d+)\s

And use captured group #1.

Upvotes: 1

Related Questions