Escaping decimal points in regular expressions
I'm trying to do something that ought to be very simple. I'm trying to test whether a string (which is an argument to a command) is a valid value of the type I need.
That is, I want it to be convertable to a double and be in the range 0.1-1.0.
I have this line in my code:
Regex ValidPause = new Regex("^((1\.0)|(0\.[1-9]))$");
The problem is that VS marks the string as bad and gives me the message "Unrecognized escape sequence." If I take out the backslashes, the red squiggly line goes away, but then it matches "0x0", which is obviously not what I want.
How should I escape the decimal points correctly?
[713 byte] By [
GailG] at [2008-2-11]
Hi.
The correct regex is
Regex ValidPause = new Regex(@"^((1\.0)|(0\.[1-9]))$");
or
Regex ValidPause = new Regex("^((1\\.0)|(0\\.[1-9]))$");
The following regex in the previous posting is wrong.
Regex ValidPause = new Regex(@"^((1.0)|(0.[1-9]))$");
Because it means.. (1 and then (any character) and then 0) or (0 and then (any character) and then 1-9).
so it match like.. 110, 1a0, 0w1, 001, 022
cheers.,
soemoe
Hi.
The correct regex is
Regex ValidPause = new Regex(@"^((1\.0)|(0\.[1-9]))$");
or
Regex ValidPause = new Regex("^((1\\.0)|(0\\.[1-9]))$");
The following regex in the previous posting is wrong.
Regex ValidPause = new Regex(@"^((1.0)|(0.[1-9]))$");
Because it means.. (1 and then (any character) and then 0) or (0 and then (any character) and then 1-9).
so it match like.. 110, 1a0, 0w1, 001, 022
cheers.,
soemoe
Actually, it does work to match what I meant it to match. I just wonder, since it does work, how you would write a regex to use a dot to match both "any character" and a decimal point.
In fact, I just ran it with the strings you list, and it doesn't match any of them.
umm....
strange...?
anyway, here is my test.
using System;
using System.Text.RegularExpressions;
public class RegexTest
{
public static void Main()
{
Regex reg1 = new Regex(@"^((1.0)|(0.[1-9]))$");
Regex reg2 = new Regex(@"^((1\.0)|(0\.[1-9]))$");
string[] strArr = {"110", "1a0", "0w1", "001", "022", "1.0", "0.9", "0.3", "0.1"};
Console.WriteLine(@"reg1 [ ^((1.0)|(0.[1-9]))$ ]");
foreach(string str in strArr)
{
if ( reg1.IsMatch(str) )
{
Console.WriteLine("Match: {0}", str);
}
else
{
Console.WriteLine("Not Match: {0}", str);
}
}
Console.WriteLine("\n");
Console.WriteLine(@"reg2 [ ^((1\.0)|(0\.[1-9]))$ ]");
foreach(string str in strArr)
{
if ( reg2.IsMatch(str) )
{
Console.WriteLine("Match: {0}", str);
}
else
{
Console.WriteLine("Not Match: {0}", str);
}
}
}
}
The output is;
reg1 [ ^((1.0)|(0.[1-9]))$ ]
Match: 110
Match: 1a0
Match: 0w1
Match: 001
Match: 022
Match: 1.0
Match: 0.9
Match: 0.3
Match: 0.1
reg2 [ ^((1\.0)|(0\.[1-9]))$ ]
Not Match: 110
Not Match: 1a0
Not Match: 0w1
Not Match: 001
Not Match: 022
Match: 1.0
Match: 0.9
Match: 0.3
Match: 0.1
Please try it yourself and reply me.
Thanks.
soemoe
P.S.. any character means one of all character including decimal, alphabetic, space, etc...