Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching multiple dots

Tags:

regex

[Editted] I'm relatively new to regex, now I am facing a use case where the target string should contain exactly ONE dot '.'. To be more specific, I'm doing a floating point detection where I believe there should contain only one dot, and an exponent "e".

My regex now looks like this: (?=.*[0-9]{1,})(?=.*[\.][0-9])(?=.*[eE][+-]?[1-9]). It seems to be working on test strings like:

2.1E12  
3.141E23

But once I test with:

1.15E10.34

It still passed.

Does anyone know what I did wrong here? Also could someone please recommend a good resource for learning regex?

Thanks!

like image 632
benjaminz Avatar asked Oct 18 '25 05:10

benjaminz


1 Answers

To validate a floating point number represented as a string, use the following pattern:

^[0-9]*\.[0-9]+([eE][0-9]+)?$

This will validate that you have:

  1. 0 or more digits in front of the decimal, but nothing else.
  2. Exactly one decimal point.
  3. At least one digit after the decimal (1. style floats not accepted)
  4. If you have an E, you have one or more digits (and only digits) after it.

This, of course, assumes that the string is only the number you're looking to test as your question suggests. We can remove any need for lookaround if that is the case.

Depending on your language, it may be more elegant to simply try to convert the string to a float, catching failures.

like image 144
Aaron W. Avatar answered Oct 21 '25 03:10

Aaron W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!