Java 获取方括号中的字符串

Java 获取方括号中的字符串,java,regex,Java,Regex,我有一个字符串:head1[00100-00228] 我需要检索方括号中的值,即00100-00228 我使用了: String a="head1 [00100 - 00228]"; replaceAll("(\\[.*?\\])", "")) 但这已经删除了方括号字符串。有人能帮我获得愿望输出吗?试试下面的代码 String a = "head1 [00100 - 00228]"; String out = a.substring(a.indexOf("[")+1,a.index

我有一个字符串:head1[00100-00228]

我需要检索方括号中的值,即00100-00228

我使用了:

String a="head1  [00100 - 00228]";    
replaceAll("(\\[.*?\\])", ""))
但这已经删除了方括号字符串。有人能帮我获得愿望输出吗?

试试下面的代码

String a  = "head1 [00100 - 00228]";
String out = a.substring(a.indexOf("[")+1,a.indexOf("]"));
希望这有帮助

您可以:

避开方括号 使用任何字符作为文本和量词 使用环顾四周。 例如:

String input = "head1 [00100 - 00228]";
//                           | follows by "["
//                           |       | any text, reluctant quantifier
//                           |       |  | followed by "]"
Pattern p = Pattern.compile("(?<=\\[).+?(?=\\])");
Matcher m = p.matcher(input);
// iterating over all matches, in case input String contains more 
// than one [...] entity
while (m.find()) {
    System.out.println("Found: " + m.group());
}

我的第一个想法是使用子字符串,如果你知道括号前字符串的长度。但后来我想到了标记器。它将字符串拆分为标记,您可以检查每个标记,看它是否以括号开头


这里有一个指向API的链接,请检查这是否是您想要的

  public static void main(String[] args) {
      String s = "head1  [00100 - 00228]";
      Pattern p = Pattern.compile(".*(\\[.*?\\]).*");
      Matcher m = p.matcher(s);
      if(m.matches()){
          System.out.println(m.group(1));
      }
}

您应该看看如何使用匹配器-您可以找到字符串的多个匹配部分:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class MatchingExample {

  private static final Logger logger = Logger.getLogger(MatchingExample.class);

  public static void main(String[] args) {
    // Pattern is: look for square bracket, start capture, look for at least one non-],
    // end capture, look for closing square bracket.
    Pattern p = Pattern.compile("\\[([^\\]]+)\\]");
    Matcher m = p.matcher("This is a [string] of [interest]");
    while (m.find()) {
      logger.info("We found: " + m.group(1));
    }
  }

}
这将打印:

We found: string
We found: interest
We found: string
We found: interest