如何使用 Java RegEx 匹配两个给定表达式中的一个表达式?
使用 Java 正则表达式的 or 逻辑运算符 | 可以匹配两个给定表达式中的任意一个表达式。
例如,如果你需要让你的正则表达式匹配多个表达式,可以通过使用“|”将需要的表达式分隔开来。
示例 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Regular expression to match string that starts with hello or ends with bye String regex = "^hello|bye$"; //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 occurred"); } else { System.out.println("Match not occurred"); } } }
输出 1
Enter a String hello how are you Match occurred
输出 2
Enter a String This is a sample string Match not occurred
示例 2
import java.util.Scanner; public class RegexExample { public static void main( String args[] ) { //Regular expression to match either yes or no String regex = "yes|no"; System.out.println("Enter input value: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); boolean bool = input.matches(regex); if(bool) { System.out.println("match occurred"); } else { System.out.println("match not accepted"); } } }
输出 1
Enter input value: yes match occurred
输出 2
Enter input value: hello match not accepted
广告