1

I know it has already been asked Here however I would like to use named group in java like Pshemo suggested and I can't figure what's wrong with my regex conversion:

Here is the python regexp:

regexp = re.compile(r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', re.DOTALL | re.MULTILINE)
matches = regexp.findall(content)

Here is my java converted regexp:

String regexp = "(?<delim>[^\\w\\n\\\"'])(?<space> ?)(?<quote>[\\\"']).*?(?=quote)(?=delim)";
Pattern pattern = Pattern.compile(regexp, Pattern.DOTALL | Pattern.MULTILINE);
Matcher matcher = pattern.matcher(content);

What I am doing wrong ?

1
  • 1
    What is the issue? Note you converted named backreferences into positive lookaheads ((?P=quote) => (?=quote)) Commented Nov 22, 2016 at 11:38

1 Answer 1

1

You converted named backreferences into positive lookaheads ((?P=quote) => (?=quote)), while you need \k<groupname>:

String regex = "(?<delim>[^\\w\n\"'])(?<space> ?)(?<quote>[\"']).*?\\k<quote>\\k<delim>";

Tested at OCPSoft regex tester:

enter image description here

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

2 Comments

Thank you, It seems to work way better than this way. It is supposed to catch the content of a line like "one", "two", "three", "four", "five". However I do not understand why it doesn't work if the spaces between the elements are removed: "one","two","three","four","five". The group spaces should match the space character 0 or 1 time, why isn't it matching when there are 0 spaces ?
You need to make the delim optional, (?<delim>[^\w\n"']?)(?<space> ?)(?<quote>["']).*?\k<quote>\k<delim> as the string starts with a quote.

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.