Java 如何提取两个分隔符之间的字符串
可能重复:Java 如何提取两个分隔符之间的字符串,java,string,split,Java,String,Split,可能重复: 我有一根像 “ABC[这是提取]” 我想提取java中的部分“这是提取”。我正在尝试使用split,但它没有按照我想要的方式工作。有人有什么建议吗?如果字符串中只有一对括号([]),可以使用indexOf(): 如果只有一次,我想伊万诺维奇的答案是最好的。但是,如果出现很多情况,则应使用regexp: \[(.*?\]这是您的模式。在每个组中(1)将为您获取字符串 Pattern p = Pattern.compile("\\[(.*?)\\]"); Matcher m = p.m
我有一根像 “ABC[这是提取]”
我想提取java中的部分
“这是提取”
。我正在尝试使用split,但它没有按照我想要的方式工作。有人有什么建议吗?如果字符串中只有一对括号([]
),可以使用indexOf()
:
如果只有一次,我想伊万诺维奇的答案是最好的。但是,如果出现很多情况,则应使用regexp:
\[(.*?\]
这是您的模式。在每个组中(1)
将为您获取字符串
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
m.group(1); //is your string. do what you want
}
尝试
试着用你试过的东西?很难知道为什么在没有看到代码的情况下您所做的工作不起作用;请参阅文档:这是我正在尝试的模式somePart=Pattern.compile(“\\b[.*?\\b]”);Matcher Matcher=somePart.Matcher(信息);有关应用上述方法函数
indexOf
和substring
对字符进行内部迭代的信息,请参阅此线程的答案。所以请记住,当您调用srt.substring(str.indexOf,str.indexOf)
originalstr
时,会迭代3次。这可能会导致大字符串的性能问题。indexOf(“[”)可能比indexOf(“[”)快一点
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
m.group(1); //is your string. do what you want
}
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);
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));