Java examples for Regular Expressions:Match
Using Pattern and Matcher Classes
import java.util.regex.Pattern; import java.util.regex.Matcher; public class Main { public static void main(String[] args) { String regex = "[abc]@."; String source = "cric@mypkg.com is a valid email address"; Main.findPattern(regex, source);/*ww w.ja v a 2 s .c o m*/ source = "asdf@mypkg.com is invalid"; Main.findPattern(regex, source); source = "a@asdf@fdsa@u"; Main.findPattern(regex, source); source = "There is an @ sign here"; Main.findPattern(regex, source); } public static void findPattern(String regex, String source) { // Compile regex into a Pattern object Pattern p = Pattern.compile(regex); // Get a Matcher object Matcher m = p.matcher(source); boolean found = false ; // Print regex and source text System.out.println("\nRegex:" + regex); System.out.println("Text:" + source); // Perform find while (m.find()) { System.out.println("Matched Text:" + m.group() + ", Start:" + m.start() + ", " + "End:" + m.end()); // We found at least one match. Set the found flag to true found = true; } if (!found) { // We did not find any match System.out.println("No match found"); } } }