給定一段文本
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()); } } }
輸出結果: