Reputation: 7305
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:
^[0-9]-
, -[0-9]-
, ^[0-9]&
, -[0-9]&
Regex.Replace(input, "^[0-9]-","0")
into something like: Regex.Replace(input, "^[0-9]-","^0[0-9]-")
Upvotes: 2
Views: 2215
Reputation: 91438
(?<!\d)(\d)(?!\d)
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