tags:

views:

41

answers:

2

Hi guys,

Here is an easy one :) on REGEX

I have this regex

"^\\$?(\\d{1,3},?(\\d{3},?)*\\d{3}(\\.\\d{2})?|\\d{1,3}(\\.\\d{2})?|\\.\\d{2}?)$"

which works on {100, $100, $100.15, $1,000, $1,000.15} and so on....

I want a simple Regex which works on numbers like : {100, 100.15} and thats all - no commas and currency symbols crap...

Thanks,

Voodoo

+2  A: 
^(\d+(\.\d{2})?|\.\d{2})$
  • \d+ one or more digits
  • (\.\d{2})? optional decimal part
  • | or
  • (\.\d{2}) or just the decimal part

If you make the integer part \d*, the regex will match an empty string.

If you can use look ahead, you can use it to make sure that the string is not empty.

^(?=.)\d*(\.\d{2})?$
Amarghosh
I'd personally use `(?!$)` and `\d\d`. Explanation gets you my vote. (Any non-trivial regexp deserves comments.)
strager
`(?!$)` sounds better than `(?=.)`. I considered `\d\d` but went for `\d{2}` as it had `2` in it - thought it reads better.
Amarghosh
in my original question I had to use escape char "\" because it was in csharp code, do you fellows know of a better way to put this in csharp code without the escape character?
VoodooChild
@VoodooChild, Use verbatim string literals: `@"^(\d+(\.\d{2})?|\.\d{2})$"` (including the `@`).
strager
Thanks guys :) (verbatim string I forgot that word before, thanks)Cheers
VoodooChild
A: 

You could try the following:

"^\d+(\.\d{1,2})?$"

This will match a number followed by an optional decimal point and 1 or two decimal places.

Josiah