Jackson
Jackson

Reputation: 3518

Regex to match all single or double digit numbers

I need to create a regex to match all occurrences of a single or double digit (surrounded with a space on each side of the digit). I am trying with this regex:

\s\d{1,2}\s

and I am running it on this string:

charge to at10d to and you 12 sdf 90 fdsf fsdf32 frere89 32fdsfdsf ball for 1 8 toyota

matches:

' 12 ', ' 90 ', ' 1 '

but it does not match the 8 when it is beside the 1. Does anyone know how I can adjust the regex so I can include both these digits together?

Upvotes: 1

Views: 5989

Answers (2)

Ori Drori
Ori Drori

Reputation: 191936

You can use the word boundry \b expression.

The word boundary will find numbers that are not wrapped by a letters, numbers or the underscore sign. It will catch 1 or 2 digits that are wrapped by spaces, start and end of string, and non word characters (#12@ - will get he 12).

var str = "51 charge to at10d to and you 12 sdf 90 fdsf fsdf32 frere89 32fdsfdsf ball for 1 8 toyota 12";

var result = str.match(/\b\d{1,2}\b/g);

console.log(result);

Upvotes: 2

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

You are trying the match both the leading and trailing space around the required number. If you just get away with one of these spaces(by using a lookahead as shown below to remove the trailing space), you will get rid of the problem.

Try this regex:

\s\d{1,2}(?=\s)

Explanation:

  • \s - matches a white-space
  • \d{1,2} - matches a 1 or 2 digit number
  • (?=\s) - returns the position(0-length match) which is followed by a space. So, it doesn't actually matches the space but makes sure that current position is followed by a space

Click for Demo

Upvotes: 5

Related Questions