0

Lets say I have the following strings:

mya!phaNum3rics-456-456-lll
zzzz-6a6-6a6-lll
vvvv-4-4-lll

These are considered matches because "second" and "third" group repeat, and last group ends with lll. What regex would allows for any character sequence in the second and third "group".

How much different if the following is also considered a match?

zasdfdf-zadezz-6a6-6a6-lll

"third to last group" repeats with "second to last group" and ends with "group" lll.

2
  • You are looking for backreferences: docs.oracle.com/javase/tutorial/essential/regex/…. Commented Oct 19, 2016 at 18:24
  • Yes, I will try backreferences. Never new this existed, especially within Java regex engine. Commented Oct 19, 2016 at 20:48

1 Answer 1

1

You need

-([^-]+)-\1-lll$

See the regex demo

  • - - a hyphen
  • ([^-]+) - Group 1 capturing one or more symbols other than -
  • - - a hyphen
  • \1 - a backreference to the text captured into Group 1
  • -lll - a substring of literal characters
  • $ - end of string.

Java demo:

String str = "mya!phaNum3rics-456-456-lll";
Pattern ptrn = Pattern.compile("-([^-]+)-\\1-lll$");
Matcher matcher = ptrn.matcher(str);
if (matcher.find()) {
    System.out.println(matcher.group(0) + " matched!");
}

A variation of the same regex for use with .matches:

if (str.matches(".*-([^-]+)-\\1-lll")) {
    System.out.println(str + " matched!");
}
Sign up to request clarification or add additional context in comments.

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.