Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for extracting all heading digits from a string

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

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();
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a word boundary \b:

\b\d+

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 ^:

^\d+

Pattern DIGITS = Pattern.compile("\\b\\d+"); // leading digits of all words
Pattern DIGITS = Pattern.compile("^\\d+"); // leading digits of input
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading