0

I have a regex but i am not able to interpret it: \w\1.

I thought it would match : aa since it had word a twice and first group would be a word for this regex. But its not behaving in this manner.

Does back referencing work only if we place parentheses around regex ?

Any help would be appreciated. Thanks.

6
  • \w\1? That's the whole regex? Are you sure this is Java? Commented Sep 8, 2013 at 18:21
  • Yes this is a very simple regex in JAVA. I am new to these regex. Commented Sep 8, 2013 at 18:22
  • (\w)\1 Captures the matched subexpression and assigns it a zero-based ordinal number. Commented Sep 8, 2013 at 18:23
  • 3
    I think in Java you need more slashes. Commented Sep 8, 2013 at 18:24
  • 1
    @d'alar'cop: Yes and no. The regex itself is okay as it is. But in Java, you construct a regex from a string, and literal strings need extra escapes for backslashes. If you were getting the regexp string from anywhere that is not a literal (from stdin, from DB...), you wouldn't write extra slashies. (That said, the regex doesn't work as intended, because as OP noticed, nothing is captured unless there's braces.) Commented Sep 8, 2013 at 18:25

2 Answers 2

7

\n refers to the nth capturing group. However, there are no capturing groups in your regex to refer to. You likely want:

(\w)\1

demo

As a Java string that would be "(\\w)\\1".

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

6 Comments

So you mean to say that capturing groups need to be enclosed in "braces"?
@Amber Yes, that's correct. Capturing group 0 always stands for the entire expression.
@Amber They are called parentheses not braces, braces serve a different purpose in regular expressions.
@Amber You are welcome, if this answer solves your problem then please accept it to show credit to the answerer.
@Sniffer I was just waiting for stackoverflow to allow me to accept the answer. (10 min) :)
|
1

(\w)\1 Captures the matched subexpression and assigns it a zero-based ordinal number.

Comments

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.