0-9 Regex Java

3 min read Jul 04, 2024
0-9 Regex Java

Digit Matching with 0-9 in Java Regex

In Java, regular expressions (regex) can be used to match patterns in strings. One common pattern to match is digits, which are characters representing numbers from 0 to 9. In this article, we will explore how to use regex to match digits in Java.

Matching a Single Digit

To match a single digit using regex in Java, you can use the following pattern:

[0-9]

This pattern matches any single character that is a digit from 0 to 9. Here's an example of how to use it in a Java program:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DigitMatcher {
    public static void main(String[] args) {
        String text = "Hello, I have 5 apples.";
        Pattern pattern = Pattern.compile("[0-9]");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            System.out.println("Found digit: " + matcher.group());
        }
    }
}

In this example, the program will output "Found digit: 5" because the pattern [0-9] matches the digit "5" in the input string.

Matching Multiple Digits

To match multiple digits, you can use the following pattern:

[0-9]+

The + symbol indicates that the preceding pattern should be matched one or more times. This pattern will match any sequence of digits, such as "123", "45", or "67890". Here's an example of how to use it in a Java program:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DigitMatcher {
    public static void main(String[] args) {
        String text = "I have 123 apples and 45 oranges.";
        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            System.out.println("Found digits: " + matcher.group());
        }
    }
}

In this example, the program will output "Found digits: 123" and "Found digits: 45" because the pattern [0-9]+ matches both sequences of digits in the input string.

Conclusion

In this article, we have learned how to use regex to match digits in Java. We can use the pattern [0-9] to match a single digit and the pattern [0-9]+ to match multiple digits. These patterns can be used in a variety of applications, such as data validation, text processing, and more.

Related Post


Featured Posts