0

I have some string, that has this type: (notice)Any_other_string (notes that : () has in this string`.

So, I want to separate this string to 2 part : (notice) and the rest. I do as follow :

private static final Pattern p1 = Pattern.compile("(^\\(notice\\))([a-z_A-Z1-9])+");
String content = "(notice)Stack Over_Flow 123";

        Matcher m = p1.matcher(content);

        System.out.println("Printing");

        if (m.find()) {
            System.out.println(m.group(0));
            System.out.println(m.group(1));
        }

I hope the result will be (notice) and Stack Over_Flow 123, but instead, the result is : (notice)Stack and (notice)

I cannot explain this result. Which regex is suitable for my purpose?

2
  • you're not matching the space character Commented Apr 20, 2013 at 11:43
  • @user2264587 yes. I have add a space. but, group 3 just 3. not Stack Over_Flow 123 Commented Apr 20, 2013 at 11:45

1 Answer 1

2

Issue 1: group(0) will always return the entire match - this is specified in the javadoc - and the actual capturing groups start from index 1. Simply replace it with the following:

System.out.println(m.group(1));
System.out.println(m.group(2));

Issue 2: You do not take spaces and other characters, such as underscores, into account (not even the digit 0). I suggest using the dot, ., for matching unknown characters. Or include \\s (whitespace) and _ into your regex. Either of the following regexes should work:

(^\\(notice\\))(.+)
(^\\(notice\\))([A-Za-z0-9_\\s]+)

Note that you need the + inside the capturing group, or it will only find the last character of the second part.

Sign up to request clarification or add additional context in comments.

1 Comment

@AntP Should've noticed that.. Goes to bed

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.