Home > Enterprise >  Regex remove both apostrophes if they exist in Python
Regex remove both apostrophes if they exist in Python

Time:10-05

I’m quit new to Regex but almost finished with my text mining script. Only one thing fails: I’m trying to remove the apostrophes between a word if they exist. I’m using re.sub for this.

For instance:

  • ‘Apple’ needs to be Apple
  • ‘apple’ needs to be apple
  • ‘[apple]’ needs to be [apple]
  • ‘(apple)’ needs to be (apple)

However: Apple’s needs to stay Apple’s because there is only one apostrophe.

How do I select both apostrophes when there is a word in between so I can delete them with re.sub? In every try I remove the entire string! Hopefully someone can help.

My code is as follows:

str_o='\'Apple\''

str_o_a = re.sub(r"\'(.*?)\'","", str_o) 

CodePudding user response:

I have a simpler idea: split by whitespace, trim leading and trailing apostrophes, join with whitespace. Avoids having to write a regular expression and handles sentences such as "She's 'her' mother's daughter".

text = "She's 'her' mother's daughter"
text = ' '.join([word.strip("'") for word in text.split()])
print(text)
# She's her mother's daughter

CodePudding user response:

The purpose of the parentheses in your regular expression was probably to capture the string you want to keep. The idiom looks like

str_o_a = re.sub(r"'([^']*)'", r"\1", str_o)

You want a raw string around the replacement, too, in order to preserve the backslash in the argument (otherwise you would be replacing with the literal string "\x01").

Notice also the preference for using a negated character class over a non-greedy "match anything" wildcard.

  • Related