0

Let's say I have code below:

Pattern pt = Pattern.compile("(?:h)?o");
Matcher m = pt.matcher("hours 123");
m.find();
System.out.println(m.group(0));

And the result is

ho

Here in regex I have a non-capturing group (?:h). Why is this group included in the final results? I just want to get "o" instead.

2
  • fyi, a non-capturing group is still part of the whole match, it is just not included in the group matches. Commented Nov 20, 2013 at 10:39
  • finally i get it. (?:h) is included in result.it just indicates that i can not use $1, it is made for performance reasons. Commented Nov 20, 2013 at 12:20

2 Answers 2

2

Your positive lookbehind is wrong. It should be this:

(?<=h)o

For more info, you can read this page: http://www.regular-expressions.info/lookaround.html

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

1 Comment

That is, if the OP wanted to do a lookbehind. Nothing in the OP's question indicates that the OP wanted to do so.
2

group(0) is the whole match. You need to

Pattern.compile("(?:h)?(o)");

and use m.group(1)

1 Comment

This is the actual answer to the OP's question, even if the other answer was OP's preferred solution.

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.