JAVA 正则表达式

对应规则

表达式对应
随意字符(特殊字符前须加 \ )该字符
\d0-9
\D非\d
\wa-z,A-Z,0-9,_
\W非\w
\s空格,Tab键
\S非\s
.任意一个字符
[ABC][…]内任意一个字符
[A-F0-9xy]指定范围的一个字符
[^A-F]指定范围外的任意一个字符
AB|CDAB或CD

匹配规则

放在表达式之后,只与前面的一个表达式相匹配

标志规则
*任意个字符(0~∞)
+至少一个字符
?0个或1个字符
{n}n个字符
{m,n}m-n个字符
{n,}至少n个字符
^字符串起始位置
$字符串结束位置

[a-z] 可以用来匹配任意位置上的小写字母: “…a…”
^[a-z]$ 应该只能匹配只有一个小写字母的行: “a”

java中的使用方式

1. (Boolean) String.matches(String)

查看是否符合规则

String regex = "^0\\d{2,3}-[1-9]\\d{5,7}$";/*\也需要转义,故需两个\\*/
regex.matches("0123-123456");//true

2. (Boolean) Metcher.matches()

查看是否符合规则

Pattern pattern = Pattern.compile("^0\\d{2,3}-[1-9]\\d{5,7}$");
Matcher matcher = pattern.matcher("0123-456789");
boolean matchers = matcher.matches();//true

3. (String) Matcher.group(int)

用 () 将字符串分组

Pattern pattern = Pattern.compile("^(0\\d{2,3})-([1-9]\\d{5,7})$");
Matcher matcher = pattern.matcher("0123-456789");
if(matcher.matchers())
{
	String whole = matcher.group(0);//"0123-456789",整个字符串
	String first = matcher.group(1);//"0123",第一个子串
	String second = matcher.group(2);//"456789",第二个子串
}

高级用法

贪婪与非贪婪匹配

?

正则表达式匹配默认使用贪婪匹配
使用?表示对某一规则进行非贪婪匹配
注意区分?的含义,例如\d??

举例:"<tr>.*?</tr>"
如果没有加这个?,则规则会变成"<tr>.*";加了?后,</tr>就不会被前者吞掉

分割、搜索与替换

1. (String[ ]) String.split(String)

用split的参数将字符串拆分,返回字符串数组。

String tags = "java, php\ 	python";
String[] arr = tags.split("\\s\\,\\");//arr = {"java", "php", "python"};

2. (Boolean) Matcher.find()

String s = "The quick brown fox jumps over the lazy dog.";
Pattern p = Pattern.compile("\\w*o\\w*", Pattern.CASE_INSENSITICE);//使大小写不敏感
Matcher m = p.matcher(s);
while(m.find())
{
	String sub = s.substring(m.start(), m.end());// "brown"  "fox"  "over"  "dog"									 
}

3. (String) String.replaceAll(String, String);

String s = "The    quick brown  	fox jumps over     the lazy dog.";
String r = s.replaceAll("\\s+"," ");//r = "The quick brown fox jumps over the lazy dog.";

反向引用:
用括号包起来的表达式,可用$n(n从1开始)反向引用。

String s2 = "a b c";
String r2 = s.replaceAll("(\\w+)","<b>$1</b>");//r2 = "<b>a</b> <b>b</b> <b>c</b>"

有个总结超全的博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值