2

Regex newbie alert please be gentle. I am having strings like:

sent = 'The type of vehicle FRFR7800 is the fastest'

I want to remove the duplicate occurence of the substring 'FR'. So the string should be:

sent = 'The type of vehicle FR7800 is the fastest'.

I think I have spent more than 2 hours reading/trying the tutorial of re and the more pythonic way of groupby and I really can't figure it out. I also searched the similar questions and most of the results are covering the case when there are I repeated same characters e.g. having strings like 'dddddaaaaaggggg' etc. A couple of them helped but I ended up deleting the all occurences of 'FR'.

For example I tried:

sent = re.sub(r'FC{1}', '', sent)
sent = re.sub(r'FC|', '', sent)

These removed completely the occurence of 'FR'. When I changed it to:

sent = re.sub(r'FC{2}', '', sent)

Nothing happened, the string remained having the 'FR' occurence repeated.

Can somebody help me with or give me a hint ?

3
  • @VishalSingh You're hardcoded FR as the substring, which I doubt is what the OP wants here. Commented Mar 4, 2021 at 4:43
  • fixed it @TimBiegeleisen regex101.com/r/Jg99O9/1 Commented Mar 4, 2021 at 4:44
  • @Vishal Singh thank you for the answer. I have also found that I don't know how to syntax it in python. I tried it and removed all occurences. I tried: sent = re.sub(r'(\w{2})\1', '', sent) Commented Mar 4, 2021 at 4:52

1 Answer 1

2
import re

sent = "The type of vehicle FRFR7800 is the fastest"
regex = r"(\w{2})\1"

print(re.sub(regex, r"\g<1>", sent))
Sign up to request clarification or add additional context in comments.

2 Comments

thank you! This solved it. Didn't realise that in the replace string parameter ( r"\g<1>" ) I could use a regular expression too.
This is nice, but be careful that you really understand the text you will work on since it replaces all pairs like this and these pair exist in English. ie. see results with "The papal cocoa-puff dispenser of hippopotamus-shaped vehicle FRFR7800 is in crisis"

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.