有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用matcher获得意外结果。组(索引)

我有以下字符串和模式:

String  = <html><body><input type="hidden" name="AvailabilityInputScheduleSelectView$market1" value="5~76AB~|VY~8001~"></input></body></html>
Pattern = AvailabilityInputScheduleSelectView$market1" value="(.*)|VY~(.*)~

我以为:

m.group(0) = 5~76AB~ (characters matching the first (.*))

m.group(1) = 8001 (characters matching the second (.*))

但我得到:

m.group(0) = VY~8001~

m.group(1) = null

m.group(2) = 8001

如果我只有2个模式(.*),我怎么能得到3个组(0,1,2)

我尝试了很多组合,但都没有达到预期的效果

我不知道在模式中使用不允许的字符是否有问题。我试着使用quote方法,但不起作用

有人能帮我吗


共 (2) 个答案

  1. # 1 楼答案

    $|中添加了转义,并在字符串末尾使用

    String str = "<html><body><input type=\"hidden\" name=\"AvailabilityInputScheduleSelectView$market1\" value=\"5~76AB~|VY~8001~\"></input></body></html>";
    Matcher m = Pattern.compile(".*AvailabilityInputScheduleSelectView\\$market1\" value=\"(.*)\\|VY~(.*)~.*").matcher(str);
    if (m.matches()) {
        System.out.println("Everything " + m.group(0));
        System.out.println("1st group: " + m.group(1));
        System.out.println("2nd group: " + m.group(2));
    }
    

    输出:

    Everything <html>..
    1st group: 5~76AB~
    2nd group: 8001
    

    尽管使用正则表达式解析HTML实际上是一个bad idea

  2. # 2 楼答案

    group(0)始终返回整个匹配的表达式,这与不带参数调用group()相同
    你的两个小组将分别在12

    你的一个组之所以是null是因为|,它在正则表达式中有特殊的含义,意思是or。由于每次只有or的一侧匹配,因此group(1)group(2)将返回null,具体取决于哪一侧不匹配。要获得所需的内容,请将|更改为\\|,以逐字匹配|字符