开发者

Regular Expression in C#

i want to validate the input of a text box so as not be empty and also to accept only decimal or integer. I have tried the following regex's: ^\S[0-9],?[0-9]$ this one allows one letter at the beginning

^\S[0-9]+,?[0-9]*$ this one althought that does not allow letters, it开发者_StackOverflow社区 requires for at least 2 numbers which is not desired.

thank you very much in advance for your time.


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

Starts with a digit, then possibly . more digits. If you'd like negative numbers

^-?\d+(\.\d+)?$

Although easier and more useful might be Double.TryParse.


I'd recommend just using a compare validator...

  <asp:CompareValidator id="Compare1" 
       ControlToValidate="TextBox1" 
       Operator="DataTypeCheck"
       Type="Double"
       runat="server"/>

It's designed to do the type of thing you are talking about without messing with all the regex...

I'll admit i'm not a fan of regex (unless truly needed). Take a look at this article:

Regular Expressions: Now You Have Two Problems


"^\d+(\.\d+)?$" ought to do it. This will match a string beginning with one or more digits, then optionally a decimal point and one or more additional digits. The decimal point and fractional part are grouped so if you have one, you need the other as well, but you can have neither.

The use of \S will match any non-whitespace character at the beginning, which is probably not what you want.


This should work ^\d{1,}.?\d{1,}$


^[\d]{1,99}[.]\d{1,99}

Is pretty much what you need. You can try it out here: http://www.gskinner.com/RegExr/


This will allow positive or negative numbers, with commas, and decimals.

However, it doesn't ensure commas are in the correct places

^-?[\d,]+\.?\d*$

passing

  • 2
  • 10
  • 10,000
  • 10,000.00
  • -10
  • -10,000
  • -10,000.00

failing

  • a123
  • asdf
  • 123a

To be honest though, regex is the wrong solution for this

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜