Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replacing with Regex
#1
Hi guys

I'm trying to figure out how to replace a string in dataframe using regex's match

In my case I want to get rid of parenthesis and what is inside it

Example: What I have

Name
1 John
2 Lucy Smart
3 Nick (Sweet)

What I expect to get

Name
1 John
2 Lucy Smart
3 Nick

I need something like:
users['Name'].replace(to_replace=r"(?P<f_name>\w+)(?P<l_name>\w+)(?P<par>\(\w+\))", value='<f_name> <l_name>', inplace=True, regex=True)

But I can't figure out how to connect between a value field and to_replace

Anyone can help?

Thanks
Naama
Reply
#2
Do you just need a general regex to remove paren and its contents?
>>> re.sub(r'\([^)]*\)', '', '3 Nick (Sweet)')
'3 Nick '
>>> re.sub(r'\([^)]*\)', '', '3 Nick Sweet')
'3 Nick Sweet'
Recommended Tutorials:
Reply
#3
Thanks!
That's what I need!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020