【问题标题】:How to extract a string between two delimiters [duplicate]如何在两个分隔符之间提取字符串[重复]
【发布时间】:2012-11-27 14:25:08
【问题描述】:

可能重复:
substring between two delimiters

我有一个类似

的字符串

"ABC[这是提取]"

我想在java中提取"This is to extract"部分。我正在尝试使用拆分,但它没有按我想要的方式工作。有人有建议吗?

【问题讨论】:

标签: java string split


【解决方案1】:

如果字符串中只有一对括号 ([]),则可以使用 indexOf():

String str = "ABC[ This is the text to be extracted ]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

【讨论】:

  • 函数 indexOfsubstring 在内部迭代字符。所以请记住,当您调用 srt.substring(str.indexOf, str.indexOf) 时,原来的 str 会被迭代 3 次。这可能会导致大字符串出现性能问题。
  • indexOf('[') 可能比 indexOf("[") 快一点
【解决方案2】:

如果只有 1 次出现,ivanovic 的答案是我猜的最好方法。但如果出现次数多,则应使用正则表达式:

\[(.*?)\]这是你的模式。并且在每个group(1) 中都会得到你的字符串。

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
    m.group(1); //is your string. do what you want
}

【讨论】:

  • 这就是我正在尝试的 Pattern somePart = Pattern.compile("\\b[.*?\\b]"); Matcher matcher = somePart.matcher(info);
  • 查看此线程的答案以应用上述方法stackoverflow.com/questions/4662215/…
【解决方案3】:

试试

String s = "ABC[ This is to extract ]";
        Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
        Matcher m = p.matcher(s);
        m.find();
        String text = m.group(1);
        System.out.println(text);

【讨论】:

    【解决方案4】:
      String s = "ABC[This is to extract]";
    
        System.out.println(s);
        int startIndex = s.indexOf('[');
        System.out.println("indexOf([) = " + startIndex);
        int endIndex = s.indexOf(']');
        System.out.println("indexOf(]) = " + endIndex);
        System.out.println(s.substring(startIndex + 1, endIndex));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-10
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 2015-10-09
      • 2020-04-19
      • 2019-04-05
      相关资源
      最近更新 更多