English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
باستخدام عمليات حسابية أو| يمكنك التحقق من أحد التعبيرات المقدمة في تعبير نمط Java.
على سبيل المثال، إذا كنت بحاجة إلى تعريف تعبير نمط لتنسق مع عدة تعبيرات، يمكنك استخدام "|" لتقسيم التعبيرات المطلوبة.
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$"; //编译正则表达式 نموذجُ نمط نمط = نموذج.compile(regex); //检索匹配器对象 Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } }
Enter a String hello how are you Match occurred
Enter a String This is a sample string Match not occurred
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"); } } }
Enter input value: yes match occurred
Enter input value: hello match not accepted