Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java RegEx를 사용하여 단어 경계를 일치시키는 방법은 무엇입니까?

<시간/>

메타 문자 "\\b"를 사용하여 단어 경계를 일치시킬 수 있습니다.

예시 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();
      String regex = "\\b";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of word boundaries: "+count);
   }
}

출력

Enter a String
this is a sample text
Number of word boundaries: 10

예시 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "\\b[a-zA-Z]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("First letter of each word from the given string: ");
      while(matcher.find()) {
         System.out.print(matcher.group()+" ");
      }
   }
}

출력

Enter sample text:
National Intelligence Agency Research & Analysis Wing
First letter of each word from the given string:
N I A R A W