我有一串这样的文字:
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
我将如何做到这一点?谢谢
答案 0 :(得分:2)
你可以这样做:
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());
答案 1 :(得分:-1)
如果要搜索子字符串,请不要使用^和$。这些是为了开始和结束时的字符串(而不是单词)尝试:
String regex_script = "/\[.*\]/";