0

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

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

2 Comments

worked great! THANKS - the issue was not being familiar with how certain escape sequences affected the pattern.
@ouotuo Hi, can you take a look at this question? stackoverflow.com/questions/34938232/…
-1

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 = "/\[.*\]/";

1 Comment

No, inside a String literal in Java, a backslash would need to be escaped again, and Java's regex-es are not delimited with a char like /.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.