.NET Framework Developer Center >
.NET Development Forums
>
Regular Expressions
>
Match whole numbers
Match whole numbers
- What could be the regular expression to replace whole numbers in a textfile?
For example
I want to replace 7 with 7.59 but not 167 with 167.59
Any ideas?
Answers
- The pattern for the number portion is still the same, but to restrict it to the above types of text you could do this:
string[] inputs = { @"\clock [t= 7]", @"\clock [t= 177]" }; string pattern = @"(?<start>\\clock\s+\[t=\s*)\b(?<!\.)(?<value>\d)(?![.,])\b(?<end>])"; foreach (string input in inputs) { Match m = Regex.Match(input, pattern); if (m.Success) { string value = m.Groups["value"].Value; Console.WriteLine("Value: {0}", value); } string result = Regex.Replace(input, pattern, "${start}${value}.59${end}"); Console.WriteLine("Original: {0}", input); Console.WriteLine("Result: {0}", result); }
I switched to named groups for clarity in the replacement pattern.
Document my code? Why do you think it's called "code"?- Marked As Answer byPilot_ Wednesday, November 04, 2009 9:18 PM
All Replies
- Try this:
string input = "7,167,5.5 1, 1.5, 23, 1,000"; string pattern = @"\b(?<!\.)(\d)(?![.,])\b"; string result = Regex.Replace(input, pattern, "$1.59"); Console.WriteLine("Original: {0}", input); Console.WriteLine("Result: {0}", result);
The "$1" in the replacement pattern refers to the captured group value. The ".59" is appended to give the result you described.
Document my code? Why do you think it's called "code"? - Hi
Apologies but the numbers I want to match are in the following form
\clock [t= 7] ( I want to match only 7)
\clock [t= 177] (but not 177) - The pattern for the number portion is still the same, but to restrict it to the above types of text you could do this:
string[] inputs = { @"\clock [t= 7]", @"\clock [t= 177]" }; string pattern = @"(?<start>\\clock\s+\[t=\s*)\b(?<!\.)(?<value>\d)(?![.,])\b(?<end>])"; foreach (string input in inputs) { Match m = Regex.Match(input, pattern); if (m.Success) { string value = m.Groups["value"].Value; Console.WriteLine("Value: {0}", value); } string result = Regex.Replace(input, pattern, "${start}${value}.59${end}"); Console.WriteLine("Original: {0}", input); Console.WriteLine("Result: {0}", result); }
I switched to named groups for clarity in the replacement pattern.
Document my code? Why do you think it's called "code"?- Marked As Answer byPilot_ Wednesday, November 04, 2009 9:18 PM


