Java正则表达式支持3个逻辑运算符,它们是-
XY:X,然后是Y
X | Y:X或Y
(X):捕获组。
这仅匹配两个连续的单个字符。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "am"; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //匹配字符串中的已编译模式 Matcher matcher = pattern.matcher(input); if (matcher.find()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } }
Enter input text: sample text Match occurred
Enter input text: hello how are you Match not occurred
这匹配“ |”周围的两个表达式/字符中的任何一个
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "Hello|welcome"; String input = "Hello how are you welcome to Nhooo"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Number of matches: "+count); } }
输出结果
Number of matches: 2
捕获组使您可以将多个字符视为一个单元。您只需要将这些字符放在一组括号内即可。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CapturingGroups { public static void main( String args[] ) { System.out.println("Enter input text"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "(.*)(\\d+)(.*)"; //创建一个Pattern对象 Pattern pattern = Pattern.compile(regex); //现在创建匹配对象。 Matcher matcher = pattern.matcher(input); if (matcher.find( )) { System.out.println("Found value: " + matcher.group(0) ); System.out.println("Found value: " + matcher.group(1) ); System.out.println("Found value: " + matcher.group(2) ); System.out.println("Found value: " + matcher.group(3) ); } else { System.out.println("NO MATCH"); } } }
输出结果
Enter input text sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: 4 Found value: (digits) in middle