Java 中的正则表达式"(re)"子表达式
javaobject oriented programmingprogramming更新于 2024/5/6 22:36:17
子表达式/元字符"( )"将正则表达式分组并记住匹配的文本。
示例 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)";
//编译正则表达式
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");
}
}
}
输出
找到匹配项
示例 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("输入输入字符串: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//使用组的正则表达式
String regex = "(?:.*)(\d+)(.*)";
//创建一个 Pattern 对象
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");
}
}
}
输出
输入输入字符串: This is a 5363 test string Match found
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

