### "Is Given String Numeric" Control with Java Regexp

This morning, i want to blog a fundemantal issue of regular expressions: "Is given string Numeric?". This seams to me so reasonable to implement and note it here for future use.

In order to grab numbers from texts, [0-9]+ inclusive range can be simply used. However; what about minus-plus signs and '.' seperator for floating numbers. Things are getting a bit more complex, in this point. It is still easy by using iterative approach to support each rule. Lets list the rules:

Lets examine the second rule; it defines the number and position of sign rules. Only one sign can exists before number.It gets better but not yet ready to publish. Since it accepts ("-.9") as a number, keep going further to find the exact expression.

And the final rule will shape the regexp pattern by defining the rule of '.' position. After the dot there must at least one digit.

In java, it is possible to use shortcuts for common regular expressions: for instance [\\d] can be used to interchange for [0-9]. Below I use this syntax.

Thanks for reading...

In order to grab numbers from texts, [0-9]+ inclusive range can be simply used. However; what about minus-plus signs and '.' seperator for floating numbers. Things are getting a bit more complex, in this point. It is still easy by using iterative approach to support each rule. Lets list the rules:

- A number contains [0-9], -, + and . characters
- A number can have only one sign(- or +) prefix
- A number can be floating digits (includes '.' precedded and followed by digits)

**[-+\\.0-9]+**Lets examine the second rule; it defines the number and position of sign rules. Only one sign can exists before number.It gets better but not yet ready to publish. Since it accepts ("-.9") as a number, keep going further to find the exact expression.

**[-+]{0,1}[0-9\\.]+**And the final rule will shape the regexp pattern by defining the rule of '.' position. After the dot there must at least one digit.

**[-+]{0,1}[0-9]+(\\.[0-9]+){0,1}**In java, it is possible to use shortcuts for common regular expressions: for instance [\\d] can be used to interchange for [0-9]. Below I use this syntax.

Pattern numberPattern = Pattern.compile("[-+]{0,1}\\d+(\\.\\d+){0,1}"); Matcher matcher = numberPattern.matcher("-2.2"); if (matcher.matches()) { // evaluates to true } matcher = numberPattern.matcher("+2.2"); if (matcher.matches()) { // evaluates to true } matcher = numberPattern.matcher("2.2"); if (matcher.matches()) { // evaluates to true } matcher = numberPattern.matcher("+3"); if (matcher.matches()) { // evaluates to true } matcher = numberPattern.matcher("-3"); if (matcher.matches()) { // evaluates to true } matcher = numberPattern.matcher("3"); if (matcher.matches()) { // evaluates to true }

Thanks for reading...