正则表达式:不情愿限定符、环视及高效表达式技巧
1. 不情愿限定符
在正则表达式中,与贪婪限定符相对的是不情愿限定符,它会尽可能少地进行匹配。不情愿限定符是在现有的贪婪限定符后面添加 ? 来构成的。例如, X+ 变为 X+? , X{n,m} 变为 X{n,m}? 等。
以下是一个示例,使用模式 \d+? 匹配候选字符串 1234 ,代码如下:
import java.util.regex.*;
public class ReluctantExample{
public static void main(String args[]){
//define the pattern
String regex = "(\\d+?)";
//compile the pattern
Pattern pattern = Pattern.compile(regex);
//define the candidate string
String candidate = "1234";
//extract a matcher for the candidate string
Matcher matcher = pattern.matcher(candidate);
while (match
超级会员免费看
订阅专栏 解锁全文
1940

被折叠的 条评论
为什么被折叠?



