正则表达式之贪婪模式与非贪婪模式

给定一段文本

https://www.example.com/ ---- http://www.sample.com.cn/ ---- 示例文本

要将其中的所有http(s)链接提取出来

先尝试使用正则表达式:https{0,1}://.+/

会发现得到的结果是https://www.example.com/ ---- http://www.sample.com.cn/

这是因为正则表达式默认采用了贪婪模式(尽可能多的匹配)

也就是说在//之后会尽可能多的进行匹配,直到遇到最后一个/

为避免这种情况,可采用非贪婪模式(尽可能少的匹配),在+后添加一个?

即https{0,1}://.+?/

以Java代码为例:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionDemo {

    public static void main(String[] args) {
        String regex = "https{0,1}://.+?/";
        String text = "https://www.example.com/ ---- http://www.sample.com.cn/ ---- 示例文本";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

输出结果:

猜你喜欢

转载自www.cnblogs.com/buyishi/p/10389976.html
今日推荐