【问题标题】:Extract string between two strings in java在java中提取两个字符串之间的字符串
【发布时间】:2013-05-16 20:55:17
【问题描述】:

我尝试在 之间获取字符串,这是我的实现:

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 ]

我哪里错了,如何改正?

【问题讨论】:

  • 您似乎将拆分字符串与模式匹配混淆了。

标签: java regex string


【解决方案1】:

你的模式很好。但是你不应该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));
}

【讨论】:

  • 我添加了Pattern.DOTALL,用于预期匹配跨越多行的非常常见的情况。
【解决方案2】:

我在这里回答了这个问题: https://stackoverflow.com/a/38238785/1773972

基本使用

StringUtils.substringBetween(str, "<%=", "%>");

这需要使用“Apache commons lang”库: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4

这个库有很多有用的处理字符串的方法,你会真正受益于在你的java代码的其他领域探索这个库!!!

【讨论】:

  • 我真的不明白为什么我们需要在项目中添加一个新的依赖 jar/library 只是为了实现一个小的琐碎功能
  • 添加依赖变成了笑话:)
  • @Stunner,你说得对,这太过分了。但这个答案主要是针对那些在类路径中已经有 commons-lang3 的人。
【解决方案3】:

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;
  }

【讨论】:

  • 当有多个匹配项时,这不会返回多个匹配项。只有第一个。
  • 虽然它只返回第一场比赛,但满足我的需要。
【解决方案4】:

您的正则表达式看起来正确,但您使用的是 splitting 而不是 matching 使用它。你想要这样的东西:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2013-12-11
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多