Java使用正则表达式

Java对正则表达式的支持并不是很好,知道JDK1.8都不能支持正则表达式中的平衡组,只能支持(?<name>exp)这样的捕获方式

平衡组中用到的表达式如下:

(?'name'子表达式A) ,若成功匹配子表达式A,则往名为name的栈空间压一个元素。
(?'-name'子表达式A) ,若成功匹配子表达式A,则弹出名为name的栈空间的栈顶元素,弹出元素后若栈空间为空则结束匹配。
(?(name)yes表达式|no表达式) ,若名为name的栈空间非空,则使用yes表达式进行匹配,否则则使用no表达式进行匹配。
(?(name)yes表达式) ,若名为name的栈空间非空,则使用yes表达式进行匹配。
(?!) ,由于没有后缀表达式,因此总会导致匹配失败并结束匹配。

java中使用正则表达式:

官网的使用解释:

A typical invocation sequence is thus
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement
boolean b = Pattern.matches("a*b", "aaaaab");
find() Attempts to find the next subsequence of the input sequence that matches the pattern.
group(int group) Returns the input subsequence matched by the previous match.
Parameters:group - The index of a capturing group in this matcher's pattern

下面来一个实际的例子:

String str = "ds=222&de=wew";
String regex = "(^|&)ds=([^&]*)(&|$)";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(str);
System.out.println(match.find()); \\打印 true,必须增加该条代码,否则下面的无法捕获
System.out.println(match.group(2)); \\打印 222</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值