有 Java 编程相关的问题?

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

java如何使用模式匹配获取特定字符后的字符串?

String tect = "A to B";
Pattern ptrn = Pattern.compile("\\b(A.*)\\b");
Matcher mtchr = ptrn.matcher(tr.text()); 
while(mtchr.find()) {
    System.out.println( mtchr.group(1) );
}

我正在获得输出A to B,但我想要to B

请帮帮我


共 (3) 个答案

  1. # 1 楼答案

    你可以把A放在你的捕获组之外

    String s  = "A to B";
    Pattern p = Pattern.compile("A *(.*)");
    Matcher m = p.matcher(s);
    while (m.find()) {
      System.out.println(m.group(1)); // "to B"
    }
    

    你也可以把绳子分开

    String s = "A to B";
    String[] parts = s.split("A *");
    System.out.println(parts[1]); // "to B"
    
  2. # 2 楼答案

    你可以在一行中完成:

    String afterA = str.replaceAll(".*?A *", ""),
    
  3. # 3 楼答案

    将模式更改为使用look behind positive断言检查A

    Pattern ptrn = Pattern.compile("(?<=A)(.*)");