简体   繁体   中英

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 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.

这应该起作用^ \\ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM