0

I checked all the related post on Stackoverflow, but none of the answers helped. I have the following items in a list:

topics\Utmutatok\Uzemeltetoi_Utmutato.dita
topics\_Reuse\Definitions\FRP_CUST_PROD_properties.xml
topics\_Reuse\Definitions\FRP_properties.xml
topics\_Reuse\Definitions\FR_Definitions.dita

I use the following lines in my python file:

kifejezes5 = re.sub(r'^(?!(?:topics/_Reuse(.*?)|^$)$|$).*$', r'@@@@@.\1', kifejezes4)

The expressions work perfectly in Notepad++, but not in my script.

When I run my script I get the error mentioned in the title. Is there any possible workaround here?

7
  • What do you think ?! and \1 mean? Commented Dec 29, 2016 at 17:26
  • 1
    You have a capturing group inside a negative lookahead. The group will never be populated, otherwise, there would be no match. Commented Dec 29, 2016 at 17:28
  • Please explain what output you need to get, say, for topics\_Reuse\Definitions\FRP_CUST_PROD_properties.xml? Commented Dec 29, 2016 at 17:36
  • the output should be: @@@@@topics\_Reuse\Definitions\FRP_CUST_PROD_properties.xml Commented Dec 29, 2016 at 17:38
  • 1
    So, re.sub(r'^(?!(?:topics/_Reuse.*)?$).*$', r'@@@@@\g<0>', s)? Commented Dec 29, 2016 at 18:12

1 Answer 1

1

The group is unmatched because the capturing group is used inside a negative lookahead. If there is a match, the group is never populated.

Instead, use

re.sub(r'^(?!(?:topics/_Reuse.*)?$).*$', r'@@@@@\g<0>', s)

See the online Python demo:

import re
s = 'topics\_Reuse\Definitions\FRP_CUST_PROD_properties.xml'
res = re.sub(r'^(?!(?:topics/_Reuse.*)?$).*$', r'@@@@@\g<0>', s)
print(res)
# => @@@@@topics\_Reuse\Definitions\FRP_CUST_PROD_properties.xml

The pattern matches:

  • ^ - start of string
  • (?!(?:topics/_Reuse.*)?$) - not followed with topics/_Reuse and then any 0+ chars up to the end of string OR just the end of string (the string cannot be empty)
  • .*$ - any 0+ chars (other than line break chars) up to the end of string.

The replacement pattern contains a \g<0> backreference to the whole match.

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

1 Comment

Thanks for the clear explanation! I misunderstood the backreferencing.... Now it's OK!

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.