pattern matching in java code example
Example 1: java regex
import java.util.regex.*;
public class RegexExample1{
public static void main(String args[]){
//1st way
Pattern p = Pattern.compile(".s");//. represents single character
Matcher m = p.matcher("as");
boolean b = m.matches();
//2nd way
boolean b2=Pattern.compile(".s").matcher("as").matches();
//3rd way
boolean b3 = Pattern.matches(".s", "as");
System.out.println(b+" "+b2+" "+b3);
}}
Example 2: pattern matching java
import java.io.*;
import java.util.*;
import java.util.Collections;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
String emailRegEx = ".+@gmail\\.com$";
Pattern pattern = Pattern.compile(emailRegEx);
List<String> list = new ArrayList();
for (int i = 0; i < num; i++){
String name = scanner.next();
String email = scanner.next();
Matcher matcher = pattern.matcher(email);
if (matcher.find()){
list.add(name);
}
}
Collections.sort(list);
for (String name : list){
System.out.println(name);
}
}
}