Reputation: 3228
[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
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:
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
Reputation: 80639
As commented by anubhava above, simply use:
^\.$
for a regex solution.
However, you can instead use a string comparison:
testString == "."
Upvotes: 0
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