user140259
user140259

Reputation: 480

Exact matches using groups in re.sub

I am trying to change words with suffixes: "-se", "-a", "-o" or "-las", putting a blank space instead of the character "-". Example: calculou-se -> calculou se. However, I want to take only exact matches. The expected result is not being brought.

import re

string = " Calulou-se"
re.sub(r"^([a-zA-Z])(-)(se|a|o|las)$", r"\1 \3", string, flags = re.IGNORECASE)
# Prints:  Calculou-se

Upvotes: 0

Views: 136

Answers (1)

Neb
Neb

Reputation: 2280

The first group can repeat any number of times. So you need to fix your regex with:

r"^([a-zA-Z]*)(-)(se|a|o|las)$" # note the '*'

Or, simpler:

re.sub(r"-(se|a|o|las)$", r" \1", string, flags = re.IGNORECASE)

Upvotes: 1

Related Questions