如何使用Java RegEx匹配两个给定表达式之一?
使用或逻辑运算符|您可以匹配两个给定表达式之一的Java正则表达式。
例如,如果您需要正则表达式匹配多个表达式,则可以用“|”分隔所需的表达式。
例子1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //从用户读取字符串 System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //正则表达式以匹配以hello开头或以bye结尾的字符串 String regex = "^hello|bye$"; //编译正则表达式 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"); } } }
输出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