example of regex in java

Example 1: java regex matcher example

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

public class MatcherExample {

    public static void main(String[] args) {

        String text    =
            "This is the text to be searched " +
            "for occurrences of the http:// pattern.";

        String patternString = ".*http://.*";

        Pattern pattern = Pattern.compile(patternString);

        Matcher matcher = pattern.matcher(text);
        boolean matches = matcher.matches();
      
      	int count = 0;
        while(matcher.find()) {
            count++;
            System.out.println("found: " + count + " : "
                    + matcher.start() + " - " + matcher.end());
        }
    }
}

Example 2: regex java

import java.io.*;
import java.util.regex.*;

public class testRegex {

    private static Pattern pattern;
    private static Matcher matcher;

    public static void main(String args[]) {
        pattern = Pattern.compile("Hugo");
        matcher = pattern.matcher("Hugo Etiévant");
        while(matcher.find()) {
            System.out.println("Trouvé !");
        }
    }
}

Tags:

Java Example