Search code examples
javaregexquantifiers

Quantifier to print only three digit numbers in a Java regular expression


What is the quantifier to print only three digit numbers in a string in Java regular expressions?

Input : 232,60,121,600,1980
Output : 232,121,600

Instead my output is coming as:

Output : 232,121,600,198

I am using (\\d{3}). What quantifier should I use in order to print only three digit numbers?


Solution

  • You need to make use of \b word boundary:

    \b\d{3}\b
    

    See demo

    In Java, use double slashes:

    String pattern = "\\b\\d{3}\\b";
    

    You do not need to use a capturing group round the whole regex, you can access the match via .group(). See IDEONE demo