Gabe
Gabe

Reputation: 50493

Simple Numeric Regex not working

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*$", "");

Upvotes: 2

Views: 301

Answers (3)

Nicolas Buduroi
Nicolas Buduroi

Reputation: 3584

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.

Upvotes: 1

Joe
Joe

Reputation: 11677

string test = "1e2e3.e4";
var s = Regex.Replace(test, @"[^\d\.]", "");

Upvotes: 0

Matt Hamilton
Matt Hamilton

Reputation: 204139

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));

Upvotes: 1

Related Questions