开发者

java regular expression find a string add it to array and then replace original

I have a string of text like this:

This is a[WAIT] test.

What I want to do is search the string for a substring that starts with [ and ends with ] Each one I find I want to add it to an ArrayList and replace substring in original string with a ^

Here is my regex:

String regex_script = "/^\\[\\]$/"; //Match a string which starts with the character [ ending in the character ] 

Here is what I have so far:

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

how would I got about doing this? Thanks


you can do:

    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());


If you are searching a substring, don't use ^ and $. Those are for beginning and at end at a string (not a word) Try:

String regex_script = "/\[.*\]/";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜