繁体   English   中英

如何抓取两个相同字符之间的字符串

[英]How to grab the string between two of the same characters

我正在尝试制作一个程序,如果给定的字符串中包含两个破折号,则返回前两个破折号之间的文本。 如果它没有至少两个破折号,它将返回它不存在。 防爆。 我有一个弦

String s = "I AM -VERY- HUNGRY"

我希望我的程序返回非常,这是两个破折号之间。 到目前为止,这是我的代码

public static String middleText(String sentence)
   {
   int count = 0;
   for (int i = 0; i < sentence.length(); i++)
   {
     if (sentence.charAt(i) == '-')
     {
        count++;
     }
   } 
   if (count >= 2)
   {
     return sentence.substring(sentence.indexOf("-") + 1);
   }
   else
   {
     return "DOES NOT EXIST";
   }
}  

但是,此代码无法产生我想要的输出。 如果将字符串I AM -VERY- HUNGRY放入此代码中,它将返回VERY- HUNGRY 我如何才能使它仅在第二个破折号之前抓住文本?

您可以使用以下行:

return sentence.substring(sentence.indexOf("-")+1, sentence.lastIndexOf("-"));

或者使用正则表达式。 有关此情况的具体Regex的链接,请参见Regex101

-(\w+)-

它符合以下条件:

  • \\w+表示至少一次+任何字母。
  • ()正在捕获组
  • -(\\w+)--字符之间捕获一个或多个字母

组合PatternMatcher以获得结果。

public static String middleText(String sentence) {
    Pattern pattern = Pattern.compile("-(\w)-");
    Matcher matcher = pattern.matcher(sentence);
    if (matcher.find()) {
        return matcher.group(1);
    } else {
        return "DOES NOT EXIST";
    }
}

您可以为此使用Pattern and Matcher(java.util.regex)

String s = "I AM -VERY- HUNGRY";
Pattern patter = Pattern.compile("-(.*)-");
Matcher matcher = patter.matcher(s);
if (matcher.find()) {
    System.out.println(matcher.group(1)); // VERY
} else {
    System.out.println("no match");
}

只需使用String的方法拆分即可。 在此处查看API 使用字符串“-”作为分隔符,如果结果数组的长度为3或更大,则结果的第二个成员为数组:

public String myMatchFinder(String arg) {
    String result = null;
    String res[] = arg.split("-", 3);
    if(res.length == 3) {
      result = res[1];
    } else {
      throw new RuntimeException("No matches found");
    }
    return result;
}

如果未找到任何模式,则“ else”块起作用。 因此,在这种情况下,将异常作为不匹配的指示符抛出,而不是返回可能与实际结果混淆的String。 (假设您的arg字符串为“您好-未找到匹配项-再见” 。在这种情况下,字符串“未找到匹配项”将是您的实际结果)。 因此,抛出Exception后,您可以将其捕获到调用代码中,并以任意方式将其作为错误处理。

您将要使用indexOf获取第一个连字符的索引,并使用lastIndexOf获取最后一个连字符的索引。 所以也许是这样的:

int firstIndex = sentence.indexOf("-");
int lastIndex = sentence.lastIndexOf("-");
return sentence.substring(firstIndex+1, lastIndex);

(注意:此代码尚未经过测试,并且不包括您提到的错误检查类型。)

一线解决方案...

return Optional.of(sentence)
    .map(Pattern.compile("(?<=-).*?(?=-)")::matcher)
    .filter(Matcher::find)
    .map(Matcher::group)
    .orElse("DOES NOT EXIST");

暂无
暂无

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

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