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

5
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个回答

3
你可以将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"

1

更改您的模式,使用正向后瞻断言检查A

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

那是一些可怕的东西。 - Staven

0

你可以用一行代码实现:

String afterA = str.replaceAll(".*?A *", ""),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接