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 最真的新春祝福语简短