正则表达式的应用

来源:互联网 发布:mac怎么翻墙上youtube 编辑:程序博客网 时间:2024/05/18 12:01

代码:

import java.util.Scanner;import org.junit.Test;public class Regex {/* * 统计单词,使用正则表达式进行切割 */ @Testpublic 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]);}}}/* * 以叠词切割字符串 */@Testpublic 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();}}


原创粉丝点击