Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a regex that matches decimal numbers but ignores hex numbers, however if a number has a space it wont work...

Patern
^(\d*\.)?\d+$


20 <- this matches :-)

0x20 <- this is ignored :-)


 20  <-this doesnt match as it has a space :-(

(20 <- this doesnt match either :-(


Can you help guys ? :-)

What I have tried:

Ive tried
^\s(\d*\.)?\d+$
and putting the \s in many different places but no-joy.
Posted
Updated 10-Apr-20 4:07am
v2

1 solution

Your "revised version":
^\s(\d*\.)?\d+$
says that a single space is required at the front, so it will only match if a single space is present.
You can get rounf that with "*" which says "zero of more of these":
^\s*(\d*\.)?\d+$
And you can modify it to allow brackets if you must:
^[\s\(]*(\d*\.)?\d+[\s\)]*$

But ... I'd use string.Trim to remove spaces from both ends, and then use Double.TryParse to convert the value to a number. If it works, great use the numeric version. If it fails, complain to the user! If he's silly enough to expect "(" to be part of a number, then that's his problem...

What I'd actually do is use a NumericUpDown for the input so he can't enter it wrong, but that's up to you ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900