Java正则表达式的使用

一、正则匹配

正则表达式只用于操作字符串数据,java标准库的正则表达式解析引擎位于java.util.regex包中。

1.1、精确匹配

正则表达式abc,它只能精确匹配字符串"abc",无法匹配到"abcd"、“ABC”、"aBc"等其它字符串。
若正则表达式中含有特殊字符,必须要用\来转义;由于\也是Java的转义字符之一,所以正则表达式\\,它匹配单个反斜杠。
精确匹配实际上等同于String.equals(),实际上用处并不大。

1.2、模糊匹配

1.2.1 单次匹配

序号正则表达式匹配说明
1. 任 何 一 个 \color{red}{任何一个} 字符
2\d 任 何 一 个 \color{red}{任何一个} 数字
3\w 任 何 一 个 \color{red}{任何一个} 单词字符(字母、数字、下划线)
4\s 任 何 一 个 \color{red}{任何一个} 空白字符(空格符、水平制表符、垂直制表符、换行符、回车符、换页符)
5\D 任 何 一 个 \color{red}{任何一个} 数字
6\W 任 何 一 个 \color{red}{任何一个} 单词字符
7\S 任 何 一 个 \color{red}{任何一个} 空白字符

1.2.2 重复匹配

序号正则表达式匹配说明
1X*X, 零 次 或 多 次 \color{blue}{零次或多次}
2X+X, 一 次 或 多 次 \color{blue}{一次或多次}
3X?X, 一 次 或 一 次 也 没 有 \color{blue}{一次或一次也没有}
4X{n}X, 恰 好 n 次 \color{blue}{恰好n次} n
5X{n,}X, 至 少 n 次 \color{blue}{至少n次} n
6X{n,m}X, 至 少 n 次 , 但 是 不 超 过 m 次 \color{blue}{至少n次,但是不超过m次} nm

1.2.3 复杂匹配

序号正则表达式匹配说明
1^ 行 的 开 头 \color{green}{行的开头}
2$ 行 的 结 尾 \color{green}{行的结尾}
3[abc] a 、 b 或 c \color{green}{a、b或c} abc
4[^abc]任何字符, 除 了 a 、 b 或 c \color{green}{除了a、b或c} abc
5[a-zA-Z] a 到 z 或 A 到 Z \color{green}{a到z或A到Z} azAZ
6ab|c|d a b 、 c 或 d \color{green}{ab、c或d} abcd
7(a)c(e) 分 组 匹 配 \color{green}{分组匹配}

二、常见操作

2.1、匹配(matches)

String input = "15812345678";
String regex = "1[358]\\d{9}";
boolean b = input.matches(regex); 
System.out.println(b);
// true
// 对于重复的匹配,建议采用如下方式
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
boolean b = m.matches();

// 等效于 boolean b = Pattern.matches(regex, input);

2.2、分割(split)

String input = "BobttttAlicemmmmmTom";
String regex = "(.)\\1+"; // 反向引用匹配到()捕获组
String[] arr = input.split(regex); 
System.out.println(Arrays.toString(arr));
// [Bob, Alice, Tom]
Pattern p = Pattern.compile(regex);
String[] arr = p.split(input);
System.out.println(Arrays.toString(arr));
// [Bob, Alice, Tom]

2.3、替换(replaceAll)

String input = "15812345678";
String regex = "(\\d{3})(\\d{4})(\\d{4})";
String s = input.replaceAll(regex, "$1****$3"); // 反向引用匹配到的字符串
System.out.println(s);
// 158****56789
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.matches())
{
	String s = m.replaceAll("$1****$3");
	System.out.println(s);
	// 158****56789
}

2.4、搜索并获取

String input = "Moderation is for cowards.";
String regex = "\\b\\w*o\\w*\\b";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
while (m.find())
{
	String s = input.substring(m.start(), m.end());
	System.out.println(s);
}
// Moderation
// for
// cowards
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值