Biểu thức con / siêu ký tự “()” nhóm các biểu thức chính quy và ghi nhớ văn bản phù hợp.
Ví dụ 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
String input = "Hello how are you welcome to Tutorialspoint";
String regex = "H(ell|ow)";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} Đầu ra
Match found
Ví dụ 2
Trong ví dụ sau, chúng tôi đang cố gắng nối một câu có các chữ số trong đó -
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
public static void main(String[] args) {
System.out.println("Enter input string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression using groups
String regex = "(?:.*)(\\d+)(.*)";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
boolean bool = matcher.matches();
if(bool) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} Đầu ra
Enter input string: This is a 5363 test string Match found