Java中的正则表达式“(re)”子表达式
子表达式/元字符“()”对正则表达式进行分组并记住匹配的文本。
例子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 Nhooo";
String regex = "H(ell|ow)";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}输出结果
Match found
例子2
在以下示例中,我们尝试匹配其中带有数字的句子-
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();
//使用组的正则表达式
String regex = "(?:.*)(\\d+)(.*)";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
boolean bool = matcher.matches();
if(bool) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}输出结果
Enter input string: This is a 5363 test string Match found
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短