2

I'm using this regex [+-]?(\d+((\.|\,)\d*)?|(\.|\,)\d+)([eE][+-]?\d+)? against the following list of numbers:

1
1.2
1.0 
1,0

1wer,043 
1dd.44
1D

My regex matches for every example in the list posted.

This is ok for the first set (1, 1.2, 1.0, 1,1) but it also returns a match for the second set (1wer,043, 1dd.44, 1D).

How can I update my regular expression to exclude the last 3 examples?

0

2 Answers 2

1

The problem seems that you are not escaping the period character. This in turn translates to match any character. I've changed your expression to:

^[+-]?(\d+((\.|\,)\d*)?|(\.|\,)\d+)([eE][+-]?\d+)?$

which should do what you are after.

An example is available here.

The extra ^ and $ at the beginning and end respectively should ensure that the string contains only numeric data. If this is not what you are after, that is, you want to use that expression to extract numerical data, then you can simply omit them.

As per @nhahtdh's comment, your expression can be improved by putting . and , in character class:

^[+-]?(\d+([.,]\d*)?|[.,]\d+)([eE][+-]?\d+)?$
Sign up to request clarification or add additional context in comments.

2 Comments

The regex can be improved by putting . and , into character class ^[+-]?(\d+([.,]\d*)?|[.,]\d+)([eE][+-]?\d+)?$
@nhahtdh: Thanks for the suggestion.
0

You should use begin (^) and end ($) metacharacters

^[+-]?(\d+((.|\,)\d*)?|(.|\,)\d+)([eE][+-]?\d+)?$

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.