java正则表达式查找字符串并将其添加到数组中,然后替换原始字符串

java正则表达式查找字符串并将其添加到数组中,然后替换原始字符串,java,android,regex,string,Java,Android,Regex,String,我有一个字符串,如下所示: This is a[WAIT] test. 我要做的是在字符串中搜索以[开头,以]结尾的子字符串 我要将找到的每个子字符串添加到ArrayList中,并将原始字符串中的子字符串替换为^ 这是我的正则表达式: String regex_script = "/^\\[\\]$/"; //Match a string which starts with the character [ ending in the character ] 以下是我到目前为止的情况: St

我有一个字符串,如下所示:

This is a[WAIT] test.
我要做的是在字符串中搜索以[开头,以]结尾的子字符串 我要将找到的每个子字符串添加到ArrayList中,并将原始字符串中的子字符串替换为^

这是我的正则表达式:

String regex_script = "/^\\[\\]$/"; //Match a string which starts with the character [ ending in the character ] 
以下是我到目前为止的情况:

StringBuffer sb = new StringBuffer();

Pattern p = Pattern.compile(regex_script); // Create a pattern to match
Matcher m = p.matcher(line);  // Create a matcher with an input string
boolean result = m.find();
        while(result) {
                m.appendReplacement(sb, "^");
                result = m.find();
        }
        m.appendTail(sb); // Add the last segment of input to the new String

我该怎么做呢?谢谢

如果您正在搜索子字符串,请不要使用^和$。这些用于字符串(不是单词)的开头和结尾,请尝试:

你可以做:

    String regex_script = "\\[([^\\]]*)\\]";

    String line = "This is a[WAIT] testThis is a[WAIT] test";
    StringBuffer sb = new StringBuffer();
    List<String> list = new ArrayList<String>();   //use to record

    Pattern p = Pattern.compile(regex_script); // Create a pattern to match
    Matcher m = p.matcher(line); // Create a matcher with an input string

    while (m.find()) {
        list.add(m.group(1));
        m.appendReplacement(sb, "[^]");
    }
    m.appendTail(sb); // Add the last segment of input to the new String

    System.out.println(sb.toString());
String regex\u script=“\\[([^\\]]*)\\]”;
String line=“这是一个[WAIT]测试这是一个[WAIT]测试”;
StringBuffer sb=新的StringBuffer();
列表=新的ArrayList()//用于记录
Pattern p=Pattern.compile(regex_脚本);//创建一个匹配的模式
匹配器m=p.Matcher(线);//使用输入字符串创建匹配器
while(m.find()){
列表。添加(m.组(1));
m、 (sb,“[^]”);
}
m、 (某人);//将最后一段输入添加到新字符串
System.out.println(sb.toString());

不,在Java中的字符串文本中,需要再次转义反斜杠,并且Java的正则表达式没有像
/
那样用字符分隔。非常好!谢谢-问题是我们不熟悉某些转义序列是如何影响模式的。@Ouoto嗨,你能看看这个问题吗?
    String regex_script = "\\[([^\\]]*)\\]";

    String line = "This is a[WAIT] testThis is a[WAIT] test";
    StringBuffer sb = new StringBuffer();
    List<String> list = new ArrayList<String>();   //use to record

    Pattern p = Pattern.compile(regex_script); // Create a pattern to match
    Matcher m = p.matcher(line); // Create a matcher with an input string

    while (m.find()) {
        list.add(m.group(1));
        m.appendReplacement(sb, "[^]");
    }
    m.appendTail(sb); // Add the last segment of input to the new String

    System.out.println(sb.toString());