您的位置:首页 > 编程语言 > Java开发

Java使用正则表达式

2016-02-04 10:58 441 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  正则表达式 java