How to use . (dot) regular expression (REGEX) in Java

1 Answer

0 votes
package javaapplication1;
   
import java.util.regex.Matcher;
import java.util.regex.Pattern;
   
public class Example {
    public static void main(String[] args) {
        // . (Any character (may or may not match line terminators))
        searchREGEX(".", "?", "1", "d", ".", "hi.");
    }
    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;
            }
            if (!found) 
                 System.out.println(String.format("%s: Not found\n", regex));
        }
    }  
}
   
   
/*
run:
    
Found "?" from index 0 to 1
Found "1" from index 0 to 1
Found "d" from index 0 to 1
Found "." from index 0 to 1
Found "h" from index 0 to 1
Found "i" from index 1 to 2
Found "." from index 2 to 3
    
*/

 



answered Jan 22, 2016 by avibootz
edited Jan 22, 2016 by avibootz

Related questions

1 answer 125 views
1 answer 200 views
1 answer 182 views
1 answer 237 views
1 answer 269 views
...