- import java.util.Scanner;
- import org.junit.Test;
- public class Regex {
- /*
- * 统计单词,使用正则表达式进行切割
- */
- @Test
- public void countWords() {
- Scanner sc = new Scanner(System.in);
- while (true) {
- String s = sc.nextLine();
- String[] ss = s.split("\\s+");// \s是分隔符,\s+表示一个或多个分隔符
- System.out.println("单词个数:" + ss.length);
- for (int i = 0; i < ss.length; i++) {
- System.out.println(ss[i]);
- }
- }
- }
- /*
- * 以叠词切割字符串
- */
- @Test
- public void reduplicatedWords() {
- String s = "abcccddefffg";
- String[] ss = s.split("(.)\\1+");// ()代表分组,.代表任意字符\1+表示和前一位一样的一个或多个
- for (int i = 0; i < ss.length; i++) {
- System.out.print(ss[i]);
- }
- System.out.println();
- }
- }
复制代码
|
|