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

Come estrarre ogni parola (inglese) da una stringa utilizzando regex in Java?

Espressione regolare “ [a-zA-Z] + “Corrispondere a una o più lettere. Pertanto, per estrarre ogni parola dalla stringa di input data -

  • compilarecompile()l'espressione superiore del metodo della classe Pattern.

  • Eludere la stringa di input necessaria comematcher()the method parameter of the Pattern class to get the Matcher object.

  • Finally, for each match, callgroup()method to get matched characters.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EachWordExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "[a-zA-Z]+";
      // Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      // Create a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("Words in the given String: ");
      while(matcher.find()) {
         System.out.println(matcher.group() + " ");
      }
   }
}

Output result

Enter sample text:
Hello this is a sample text
Words in the given String:
Hello
this
is
a
sample
text
Potrebbe piacerti anche