在Java中提取两个字符串之间的字符串

60
我试图获取在<%= 和 %>之间的字符串,这是我的实现:

我试图获取在<%=和%>之间的字符串,这是我的实现:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>");
String[] result = pattern.split(str);
System.out.println(Arrays.toString(result));

它返回

[ZZZZL ,  AFFF ]

但是我的期望是:

[ dsn , AFG ]

我错在哪里,如何纠正?


5
似乎你把“分割字符串”和“模式匹配”混淆了。 - Brian Roach
4个回答

96

你的模式是正确的。但你不应该用split()将其分割掉,而应该使用find()函数找到它。下面的代码输出了你要找的内容:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

2
我为那些预期匹配跨越多行的常见情况添加了 Pattern.DOTALL - Wiktor Stribiżew

60

6
为了实现一个小的琐碎功能,为什么我们需要将一个新的依赖jar/库整体添加到项目中,我真的不明白。 - Stunner
4
添加依赖项已经成为一个笑话 :) - Stunner
4
@Stunner,你是正确的,这有些过头了。但这个答案主要是为那些已经在类路径中拥有commons-lang3的人准备的。 - Bogdan Kobylynskyi

8

Jlordo的方法适用于特定情况。如果您试图将其构建为抽象方法,则可能难以检查“textFrom”是否在“textTo”之前。否则,该方法可能会返回文本中其他“textFrom”的匹配项。

以下是一个已准备好的抽象方法,它解决了这个缺点:

  /**
   * Get text between two strings. Passed limiting strings are not 
   * included into result.
   *
   * @param text     Text to search in.
   * @param textFrom Text to start cutting from (exclusive).
   * @param textTo   Text to stop cuutting at (exclusive).
   */
  public static String getBetweenStrings(
    String text,
    String textFrom,
    String textTo) {

    String result = "";

    // Cut the beginning of the text to not occasionally meet a      
    // 'textTo' value in it:
    result =
      text.substring(
        text.indexOf(textFrom) + textFrom.length(),
        text.length());

    // Cut the excessive ending of the text:
    result =
      result.substring(
        0,
        result.indexOf(textTo));

    return result;
  }

当有多个匹配项时,此代码仅返回第一个匹配项,不会返回多个匹配项。 - Wheel Builder
虽然它只返回第一个匹配项,但已经满足了我的需求。 - Ajay Kumar

5
您的正则表达式看起来是正确的,但是您使用它进行了分割而不是匹配。您需要像这样做:
// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

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