Java 正则表达式程序在每个空格和标点符号处拆分字符串。

javaobject oriented programmingprogramming更新于 2024/8/1 10:56:00

正则表达式 "[!._,'@?//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("匹配数:"+count);
   }
}

输出

匹配数:8

String 类的 split() 方法接受表示正则表达式的值,并将当前字符串拆分为标记(单词)数组,将两个匹配出现之间的字符串视为一个标记。

例如,如果您将单个空格"""作为分隔符传递给此方法并尝试拆分字符串。此方法将两个空格之间的单词视为一个标记,并返回当前字符串中的单词数组(空格之间)。

因此,要在每个空格和标点符号处拆分字符串,请通过将上面指定的正则表达式作为参数传递来调用 split() 方法。

示例

import java.util.Scanner;
导入 java.util.StringTokenizer;
public class RegExample {
   public static void main( String args[] ) {
      String regex = "[!._,'@? ]";
      System.out.println("输入字符串:");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      StringTokenizer str = new StringTokenizer(input,regex);
      while(str.hasMoreTokens()) {
         System.out.println(str.nextToken());
      }
   }
}

输出

输入字符串:
This is!a.sample text,with punctuation!marks@and_spaces
This
is
a
sample
text
with
punctuation
marks
and
spaces

相关文章