정규식 "[!._,'@?//s]"는 모든 구두점 및 공백과 일치합니다.
예시
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
String input = "This is!a.sample"text,with punctuation!marks";
Pattern p = Pattern.compile("[!._,'@?//s]");
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
} 출력
Number of matches: 8
split() String 클래스의 메소드는 정규식을 나타내는 값을 받아들이고 현재 문자열을 토큰 배열(단어)로 분할하여 두 일치 항목 사이의 문자열을 하나의 토큰으로 처리합니다.
예를 들어, 이 메서드에 구분 기호로 단일 공백 " "을 전달하고 문자열을 분할하려고 시도하는 경우. 이 메서드는 두 공백 사이의 단어를 하나의 토큰으로 간주하고 현재 문자열에서 단어 배열(공백 사이)을 반환합니다.
따라서 모든 공백과 구두점에서 문자열을 분할하려면 위에서 지정한 정규식을 매개변수로 전달하여 split() 메서드를 호출합니다.
예시
import java.util.Scanner;
import java.util.StringTokenizer;
public class RegExample {
public static void main( String args[] ) {
String regex = "[!._,'@? ]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
StringTokenizer str = new StringTokenizer(input,regex);
while(str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
} 출력
Enter a string: This is!a.sample text,with punctuation!marks@and_spaces This is a sample text with punctuation marks and spaces