How to use \D regular expression (REGEX) (Any non-digit) in Java

1 Answer

0 votes
import java.util.regex.Matcher;
import java.util.regex.Pattern;
      
public class Example {
     private static void searchREGEX(String regex, String... search) {
        Pattern pattern = Pattern.compile(regex);
         
        for (String input : search) {
            Matcher matcher = pattern.matcher(input);
    
            boolean found = false;
             
            while (matcher.find()) {
                System.out.println(String.format("Found" + " \"%s\" " + "from index %d to %d",
                                            matcher.group(), matcher.start(), matcher.end()));
                found = true;
            }
             
            System.out.println();
             
            if (!found) {
                System.out.println(String.format("%s: \"%s\" Not found\n", regex, input));
            }
        }
    }  
    public static void main(String[] args) {
        // \D   (A non-digit: [^0-9])
        searchREGEX("\\D", "?", "1", "f35", ".", "012", "abc");
    }
}
      
     
      
/*
run:
  
Found "?" from index 0 to 1
 
 
\D: "1" Not found
 
Found "f" from index 0 to 1
 
Found "." from index 0 to 1
 
 
\D: "012" Not found
 
Found "a" from index 0 to 1
Found "b" from index 1 to 2
Found "c" from index 2 to 3
       
*/

 



answered May 14, 2024 by avibootz

Related questions

1 answer 269 views
2 answers 281 views
1 answer 199 views
2 answers 160 views
1 answer 182 views
1 answer 237 views
...