Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

regex - How to detect a floating point number using a regular expression

What is a good regular expression for handling a floating point number (i.e. like Java's Float)

The answer must match against the following targets:

 1) 1.  
 2) .2   
 3) 3.14  
 4) 5e6  
 5) 5e-6  
 6) 5E+6  
 7) 7.e8  
 8) 9.0E-10  
 9) .11e12  

In summary, it should

  • ignore preceding signs
  • require the first character to the left of the decimal point to be non-zero
  • allow 0 or more digits on either side of the decimal point
  • permit a number without a decimal point
  • allow scientific notation
  • allow capital or lowercase 'e'
  • allow positive or negative exponents

For those who are wondering, yes this is a homework problem. We received this as an assignment in my graduate CS class on compilers. I've already turned in my answer for the class and will post it as an answer to this question.

[Epilogue] My solution didn't get full credit because it didn't handle more than 1 digit to the left of the decimal. The assignment did mention handling Java floats even though none of the examples had more than 1 digit to the left of the decimal. I'll post the accepted answer in it's own post.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just make both the decimal dot and the E-then-exponent part optional:

[1-9][0-9]*.?[0-9]*([Ee][+-]?[0-9]+)?

I don't see why you don't want a leading [+-]? to capture a possible sign too, but, whatever!-)

Edit: there might in fact be no digits left of the decimal point (in which case I imagine there must be the decimal point and 1+ digits after it!), so a vertical-bar (alternative) is clearly needed:

(([1-9][0-9]*.?[0-9]*)|(.[0-9]+))([Ee][+-]?[0-9]+)?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...