2

I would like to strip a string to have only numeric values and one decimal point.... What is wrong with my Regex?

string test = "1e2e3.e4";
var s = Regex.Replace(test, "^\\d*\\.\\d*$", "");
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • 1
    You're using a regex for matching, but them replacing? The regex is fine to match what you're looking for. But if you want to replace away invalid characters, you'll need to define what you want out. Given `1.2.3.4`, what should be the result? `123.4`? `1.234`? `12.34`? etc... – ircmaxell Feb 10 '11 at 04:06
  • I just want to allow only numbers and decimals points. I will handle a multiple decimal point in a different way depending on some properties of my control... Is that possible? – Gabe Feb 10 '11 at 04:10

3 Answers3

1

What you're doing is striping away a decimal number, try this instead:

Regex.Replace(test, "[^\\d.]", "");

If you want to keep just one dot, you first need to determine which dot you want to keep if there's many of them.

Update: Assuming you'd want to keep the first or last dot, use String.IndexOf or String.LastIndexOf to split the string and use:

Regex.Replace(test, "\\D", "");

on each of the resulting strings. That would be potentially slower than not using regex as in Matt Hamilton answer tough.

Nicolas Buduroi
  • 3,565
  • 1
  • 28
  • 29
1

Regex might be overkill for your needs.

string test = "1e2e3.e4.56543fds.4";

var foundPeriod = false;

var chars = test.Where(c => Char.IsDigit(c) 
    || (c == '.' && !foundPeriod && (foundPeriod = true))).ToArray();

Console.WriteLine(new String(chars));
Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
  • wow, very clever. didn't know that assignment returned a value ... http://stackoverflow.com/questions/3807192/why-do-assignment-statements-return-a-value – roman m Feb 10 '11 at 04:39
0
string test = "1e2e3.e4";
var s = Regex.Replace(test, @"[^\d\.]", "");
Joe
  • 11,147
  • 7
  • 49
  • 60