Java regex 程序,用于按每个空格和标点符号分割字符串。
正则表达式 "[!._,'@?//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()方法接受一个表示正则表达式的值,并将当前字符串分割为由标记(单词)组成的数组,将两次匹配之间出现的字符串视为一个标记。
例如,如果你将单个空格“ ”作为分隔符传递给此方法并尝试分割一个字符串。此方法将两个空格之间的单词视为一个标记,并返回当前字符串中单词(空格之间)的数组。
因此,若要按每个空格和标点符号分割字符串,请对其调用 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP