取代正则表达式组结果 - 是否可能?

时间:2015-03-17 09:04:57

标签: java regex

我想验证HTML链接,同时提取" http / https",主机和地址部分。是否可以更改第1组值,如果它是" https" - 输出将是" true"值:

String url = "https://www.youtube.com/watch?v=1M9TJpLTcw8   ";

Pattern p = Pattern.compile("^(?i)(https?)://(.{3,}?)/(.*?) *$");//(?i) - for case insensitive
Matcher m = p.matcher(url);
if (m.find()) {
    System.out.println("g1: " + m.group(1));
    System.out.println("g2: " + m.group(2));
    System.out.println("g3: " + m.group(3));
}

输出结果为:

g1: https//But I want to replace it - when "http" - it would be "false", "https" - "true"
g2: www.youtube.com
g3: watch?v=1M9TJpLTcw8

2 个答案:

答案 0 :(得分:1)

怎么样?
g1 = "http".equals(m.group(1)) ? "false" : "true"

答案 1 :(得分:0)

试试这个

System.out.println("g1: " + (m.group(1) != null && m.group(1).equals("https")) ? true : false);