nick zoum
nick zoum

Reputation: 7305

Replace [0-9] with 0[0-9]

I would like to know if there is a way to add a 0 in front of every 1 digit number using regex.

The input string is a list of 1-3 numbers separated by a '-' (i.e. 28, 12-56, 67-6, 45-65-46).

The two issues I have come across are:

  1. Matching all the possible 1 digit numbers without doing a seperate check for each of the below: ^[0-9]-, -[0-9]-, ^[0-9]&, -[0-9]&
  2. Adding the 0 without removing anything else. So turn: Regex.Replace(input, "^[0-9]-","0") into something like: Regex.Replace(input, "^[0-9]-","^0[0-9]-")

Upvotes: 2

Views: 2215

Answers (1)

Toto
Toto

Reputation: 91438

  • search: (?<!\d)(\d)(?!\d)
  • replace 0$1

Where:

  • (?<!\d) is a negative lookbehind that makes sure we haven't a digit before the match.
  • (\d) is a capture group, that is referenced by $1 in the replacement part.
  • (?!\d) is a negative lookahead that makes sure we haven't a digit after the match.

See lookaround for info.

This replaces digit not preceeded or followed by other digit by 0 + the digit.

Regex.Replace(input, @"(?<!\d)(\d)(?!\d)","0$1")

Upvotes: 5

Related Questions