正则表达式
符合一定规则的表达式
1:判断QQ号是否合法(5~15位 不能以0开头 只能是数字)--------------------------------------匹配
matches(String regex)
告知此字符串是否匹配给定的正则表达式。

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); while(s.hasNext()){ String string = s.nextLine(); checkQQ(string); } s.close(); } public static void checkQQ(String string){ String regex = "[1-9][0-9]{4,14}"; if(string.matches(regex)){ System.out.println("合法"); } else{ System.out.println("不合法"); } } }
0~9:\d 而出现在字符串中为 "\\d" 非0~9 \D
\w 单词字符(包括下划线) \W 非单词字符
采用Greedy数量词 ? 一次或零次 * 任意次 + 一次或多次 {n} 恰好n次 {n,} 至少n次 {n,m} n到m次(包含n和m)
-----------------------------------------------------------------------------------------------------------------------------------------------
2:切割 按 '.' 字符切 正则表达式为 "\\." \ 都是成对出现
为了让规则的结果被重用,可以将规则封装成一个组,用()完成。组的出现都有编号,从1开始,想要使用已有的组可以通过 \n(n就是组的编号)的形式来
编号顺序按左括号算
题意:将一字符串按照叠词切割

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); while(s.hasNext()){ String string = s.nextLine(); String[] strings = splitDemo(string); for (String string2 : strings) { System.out.println(string2); } } s.close(); } public static String[] splitDemo(String string){ String regex = "([a-z])\\1+"; String[] strings = string.split(regex); return strings; } }
-----------------------------------------------------------------------------------------------------------------------------------------------
3:替换
题意:将一字符串中的叠词换成一个单词
$1 代表前一个正则表达式的第一组

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); while(s.hasNext()){ String string = s.nextLine(); System.out.println(replaceAllDemo(string)); } s.close(); } public static String replaceAllDemo(String string){ String string2 = string.replaceAll("([a-z])\\1+", "$1"); return string2; } }
4:获取-----------将字符串中符合规则的子串取出
操作步骤:
1、将正则表达式封装成对象
2、让正则对象和要操作的字符串相关联
3、关联后,获取正则匹配引擎
4、通过引擎进行所有操作,包括取出
题意:将一个字符串中单词长度为4的单词取出并给出单词的索引位
"\\b" 代表单词边界符

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); while (s.hasNext()) { String string = s.nextLine(); getDemo(string); } s.close(); } public static void getDemo(String string) { String reg = "\\b[a-zA-Z]{4}\\b"; Pattern p = Pattern.compile(reg); Matcher m = p.matcher(string); while(m.find()) { System.out.println(m.group()); System.out.println(m.start()+" "+m.end()); } } }