English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

如何使用Java RegEx匹配n次出现的表达式?

Java提供的贪婪量词使您可以匹配多次出现的表达式。哪里,

  • Exp {n}促使表达式exp恰好出现n次。

  • Exp {n,}促使表达式exp至少出现n次。

  • Exp {n,m}促使表达式exp至少出现n次,最多m次。

例子1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      //正则表达式接受5个字母的单词
      String regex = \\\";w{5}\\";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //创建一个Pattern对象
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         // Creare un oggetto Matcher
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println(input[i]+": accettato");
         } else {
            System.out.println(input[i]+": non accettato");
         }
      }
   }
}

Risultato di output

Inserisci 5 stringhe di input:
rama
raja
raghu
megha
malya
rama: non accettato
raja: non accettato
raghu: accettato
megha: accettato
malya: accettato

例子2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      //正则表达式匹配长度为2到6的非单词字符串
      String regex = \\\";W{2,6}\\";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //创建一个Pattern对象
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         // Creare un oggetto Matcher
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println(input[i] + " matched");
         }
      }
   }
}

Output 1

Inserisci 5 stringhe di input:
hello how are you
#$#%
#
#$@%%#&#&
text di esempio
#$#% matched
#$@%%#&#& matched

Esempio 3

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[] ) {
      String regex = "[a-zA-Z]{1,20}";
      Scanner sc = new Scanner(System.in);
      System.out.println("Inserisci il nome dello studente:");
      String name = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(name);
      if(m.matches()) {
         System.out.println("Il nome è appropriato");
      } else {
         System.out.println("Il nome è inappropriato");
      }
   }
}

Risultato di output

Inserisci il nome dello studente:
Mouktika
Il nome è appropriato