Thufir
Thufir

Reputation: 8487

Using pattern matching to find String data with no digits in Java

Looking to match only String's with no digits, using \D from regex.

Every string shows as false, but why?

Output:

thufir@dur:~/NetBeansProjects/parseCSV$ 
thufir@dur:~/NetBeansProjects/parseCSV$ gradle run

> Task :run                                                                                     
Feb. 16, 2020 5:24:49 A.M. parseCSV.FileHelper processLines
INFO:           false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: z10               false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: y9                false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: x7                false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: atrib6            false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: alice             false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: home5             false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: cell4             false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: sue               false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: phone3            false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: phone2            false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: phone1            false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: joe               false
Feb. 16, 2020 5:24:50 A.M. parseCSV.FileHelper processLines
INFO: people            false

BUILD SUCCESSFUL in 1s
3 actionable tasks: 1 executed, 2 up-to-date
thufir@dur:~/NetBeansProjects/parseCSV$                          

relevant method from class:

public void processLines() {
    String regex = "\\D";
    boolean isDigit = false;
    for (String s : lines) {
        isDigit = Pattern.matches(regex, s);
        log.info(s + "\t\t" + Boolean.toString(isDigit)
        );

    }

Upvotes: 0

Views: 28

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521053

You should be using the regex pattern ^\D+$, which matches one or more continuous non digit characters from start to end. Since Pattern#matches implicitly covers the entire string, we can just use \D+:

public void processLines() {
    String regex = "\\D+";
    boolean isDigit = false;
    for (String s : lines) {
        isDigit = Pattern.matches(regex, s);
        log.info(s + "\t\t" + Boolean.toString(isDigit)
        );
    }
}

Upvotes: 1

Related Questions