0
votes

I've looked through the many variations of this question have been posted before, but I still need help putting together a solution. I appreciate any help.

The alternative to a non-fixed width regex look behind seems to be creating a capture group. Can someone please help with the syntax to solve the following?

Suppose there are different sentences with the words "account", "credit" and "debit" in them. I'd like to match the ones that talk about an account being debited. So I want to eliminate matching a string that talks of it being credited. How can I match the word "account" when it is not preceded by "credit" but is followed/preceded by "debit"?

Here is my attempt at excluding the string "credit" while matching "account".

(?<!(\bcredit))(.account)

"credit your account" - fails to eliminate "credit"

"considering crediting your account promptly" - fails to eliminate "credit"

"credit account"- eliminates "credit" but only thanks to the "." in the regex.

I'd like to make the . into .{0,20} but that will not make if behave as intended.

Appreciate any help or feedback

1
Sorry, are you extracting or replacing? I guess you are planning to use it in re.sub, right? Check this approach. - Wiktor Stribiżew
Thank you for the solution, please let me dissect and think about it for some time. What I was doing is just counting the occurences with this: len(re.findall(regex_expression,string_to_lookin)) - Kdog
Ok, I see you already got a solution. - Wiktor Stribiżew

1 Answers

0
votes

You can work by selecting the strings that do not match the word combination with a simple regular expression:

import re

s1 = "credit your account"
s2 = "considering crediting your account promptly"
s3 = "credit account"
s4 = "we are debiting your account"

pattern = '.*(credit.*account|account.*credit).*'

print(re.match(pattern, s1))
print(re.match(pattern, s2))
print(re.match(pattern, s3))
print(re.match(pattern, s4))

The output is:

<_sre.SRE_Match object; span=(0, 19), match='credit your account'>
<_sre.SRE_Match object; span=(0, 43), match='considering crediting your account promptly'>
<_sre.SRE_Match object; span=(0, 14), match='credit account'>
None

You can use only the parenthesized part of the regex if you use re.search().

After you have the stings of interest (the ones that don't match), you can apply another regular expression to retrieve parts from it.