"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:
  1. A number contains [0-9], -, + and . characters
  2. A number can have only one sign(- or +) prefix
  3. A number can be floating digits (includes '.' precedded and followed by digits)
Take the first step into first rule, and try following pattern.Without any other case that defines in more detail; this must satisfy the rule of being a number. This regexp will fail to evaluate this text ("-.+") to true; and obviously it is not a number. Forget it...
[-+\\.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...

Popular posts from this blog

SoapUI 4.5.0 Project XML File Encoding Problem

COMRESET failed (errno=-32)

SoapUI - Dynamic Properties - Getting Current Time in DateTime Format