benjaminz
benjaminz

Reputation: 3228

Regex matching multiple dots

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

Upvotes: 4

Views: 6186

Answers (3)

Aaron W.
Aaron W.

Reputation: 155

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.

Upvotes: 4

hjpotter92
hjpotter92

Reputation: 80639

As commented by anubhava above, simply use:

^\.$

for a regex solution.

However, you can instead use a string comparison:

testString == "."

Upvotes: 0

user5405790
user5405790

Reputation:

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

Upvotes: 0

Related Questions