繁体   English   中英

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

[英]Extract string between two strings in java

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

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 ]

我错在哪里以及如何纠正它?

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

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

基本上用

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

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

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

你的正则表达式看起来是正确的,但你正在splitting它而不是与之matching 你想要这样的东西:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM