I am trying to extract all heading digits from a string using Java regex without writing additional code and I could not find something to work:
"12345XYZ6789ABC"
should give me "12345"
.
"X12345XYZ6789ABC"
should give me nothing
JavaScript
x
public final class NumberExtractor {
private static final Pattern DIGITS = Pattern.compile("what should be my regex here?");
public static Optional<Long> headNumber(String token) {
var matcher = DIGITS.matcher(token);
return matcher.find() ? Optional.of(Long.valueOf(matcher.group())) : Optional.empty();
}
}
Advertisement
Answer
Use a word boundary b
:
JavaScript
bd+
See live demo.
If you strictly want to match only digits at the start of the input, and not from each word (same thing when the input contains only one word), use ^
:
JavaScript
^d+
JavaScript
Pattern DIGITS = Pattern.compile("\b\d+"); // leading digits of all words
Pattern DIGITS = Pattern.compile("^\d+"); // leading digits of input