Java/RegEx - How to find the first non-word number in a string?

Viewed 123

I want a regular expression that matches based on this rule: searching for the first number in a string and checking if it's alone in its neighborhood (the character before and after the number is SPACE, or the character before is SPACE and it's the ending part of the string).

A few examples below:

  • ABC AB34.1 ABC 39.25 AB : 39.25
  • ABC AB34.1 ABC 39.25 : 39.25
  • ABC 34.1AB ABC 39.25 : 39.25

I know that /^[^\d]*(\d+)/ can match the first number in the string, but I don't know how to check if it contains SPACES before and after itself, or SPACE before and maybe \n after.

Thanks in advance.

2 Answers

You can use

(?!^)\b(?<!\d\.)\d+(?:\.\d+)?
(?!\A)\b(?<!\d\.)\d+(?:\.\d+)?

See the regex demo. In Java, after initializing the Matcher object, execute it inside an if block (not while) to get the first match.

Pattern details:

  • (?!^) - not at the start of string (\A is an unambiguous string start anchor)
  • \b - word boundary
  • (?<!\d\.) - a negative lookbehind that matches a location not immediately preceded with a digit and .
  • \d+(?:\.\d+)? - the consuming pattern part that matches one or more digits and then an optional sequence of . and one or more digits.

See the regex demo.

See the Java demo:

String s = "34.1 ABC AB34.1 ABC 39.25 AB : 19.15";
Pattern pattern = Pattern.compile("(?!^)\\b(?<!\\d\\.)\\d+(?:\\.\\d+)?");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
    System.out.println(matcher.group()); 
} else {
    System.out.println("No match found in '" + s + "'!"); 
}
// => 39.25

[^\d]+[\s]+([\d]+[.]+[\d]+)[\s]+

In English, basically this string checks if

  • one or zero non-digits
  • one or zero spaces
  • digits (with one possible decimal point)
  • one or zero spaces.

https://regex101.com/r/0DQvDd/1

Related