0

I need to convert the following python regexp to java regexp:

regexp = re.compile(r"^(?P<prefix>(%s)(%s)?)\s?\b(?P<name>.+)" %
                                ("|".join(array1),
                                 "|".join(array2)), re.IGNORECASE
                                                             | re.UNICODE)

where array1 and 2 are arrays of strings.

What I did is:

String regexp = String.format("^(?<prefix>(%s)(%s)?)\\s?\\b(?<name>.+)", array1, array2);
regexpPattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);

But I get a PatternSyntaxException: "Unknown look-behind group near" in the question mark of (%s)(%s)?

I don't understand very well this question mark.

Any suggestion on how to translate it into Java 1.6?

1
  • Hint: the python syntax makes use of named capture groups. If you understand what the python regex does, you should be able to translate it! Commented Mar 24, 2014 at 9:03

1 Answer 1

1

Tons of things will go wrong for you.

The (?< is a positive look-behind expression in java.

(?P<prefix> is a named group in python, there are no named groups in java.

String.format for %s and an array will not produce | joined strings from array like you do in python example.

First you will need to join strings by | from arrays manually. Then when you have two strings, you can do: regexpPattern = Pattern.compile(String.format("^((?:%s)(?:%s)?)\\s?\\b(.+)", string1, string2));

What was prefix group in python is now group 1 in java and name group is group 2.

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

2 Comments

Thanks a lot, it works perfectly now! OK, named groups don't exist in java. After the pattern compilation, I use the replaceAll function calling the named groups by $1 and $2. And yes, I need to concat my arrays of strings. Thanks for your useful help.
there are no named groups in java. Nonsense. (?<name>regex) works fine in Java as named group, but it was introduced in Java 7. (?<=...) or (?<!...) are look-behind (positive and negative).

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.