正則表達式之貪婪模式與非貪婪模式


給定一段文本

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

要將其中的所有http(s)鏈接提取出來

先嘗試使用正則表達式:https{0,1}://.+/

會發現得到的結果是https://www.example.com/ ---- http://www.sample.com.cn/

這是因為正則表達式默認采用了貪婪模式(Greedy,盡可能多的匹配)

也就是說在//之后會盡可能多的進行匹配,直到遇到最后一個/

為避免這種情況,可采用非貪婪模式(Non-greedy,盡可能少的匹配),在+后添加一個?

即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());
        }
    }
}

輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM