正则表达式“ [!._,'@?// 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
String类的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