regex: find one-digit number

Use word boundaries. Note that the range quantifier {1} (a single \d will only match one digit) and the character class [] is redundant because it only consists of one character.

\b\d\b

First of all, [\d]{1} is equivalent to \d.

As for your question, it would be better to use a zero width assertion like a lookbehind/lookahead or word boundary (\b). Otherwise you will not match consecutive single digits because the leading space of the second digit will be matched as the trailing space of the first digit (and overlapping matches won't be found).

Here is how I would write this:

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

This means "match a digit only if there is not a non-whitespace character before it, and there is not a non-whitespace character after it".

I used the double negative like (?!\S) instead of (?=\s) so that you will also match single digits that are at the beginning or end of the string.

I prefer this over \b\d\b for your example because it looks like you really only want to match when the digit is surrounded by spaces, and \b\d\b would match the 4 and the 5 in a string like 192.168.4.5

To allow punctuation at the end, you could use the following:

(?<!\S)\d(?![^\s.,?!])

Add any additional punctuation characters that you want to allow after the digit to the character class (inside of the square brackets, but make sure it is after the ^).


Search around word boundaries:

\b\d\b

As explained by the others, this will extract single digits meaning that some special characters might not be respected like "." in an ip address. To address that, see F.J and Mike Brant's answer(s).

Tags:

Regex