4

[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!

3
  • Do you mean that the target string should be exactly the string "."? Or that it should start with exactly one dot? Or that it must contain exactly one dot? Or something else? Commented Oct 10, 2015 at 16:59
  • I just edited the question to be more specific, please let me know if you guys need more intel. Thanks a million! Commented Oct 10, 2015 at 17:13
  • Which programming language are you using ? Commented Oct 10, 2015 at 20:49

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

A) If you want to match only '.' ( a string with len 1 and char[0] == '.', you can use

^\.$

B) If you want to match any string with any length, with only 1 dot, you are use

[^\.]\.[^\.]

Can you please drop a comment to tell me you want which case (A / B), I can help to refine the answer

1 Comment

Sorry my example was a little abstract, my use case, as I just edited the question, is to validate a floating point.
0

As commented by anubhava above, simply use:

^\.$

for a regex solution.

However, you can instead use a string comparison:

testString == "."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.