Ruben Bob
Ruben Bob

Reputation: 91

re.sub delete 8 characters after string

I've been searching around for awhile and haven't had any luck in what i'm searching for. Simply put I have a long string and i want to remove the unique identifier from it in this case JF32-000001007. However i can't seem to find the correct way to do it using re.sub.

I thought that maybe I could do something to the affect of: * = wild card in example Find: J****-********* and replace with nothing. The reason i kept J and - in there is because they are consistent. Everything else changes. What i've come up so far is the below:

import re
string = "E/Exception ['thisdevice:JFW32-000001007.IdName = telephonepole (null) has no hope, magic will be discard']"

final = re.sub(r'J.*?-', '', string)
print final

This just replaces the first half but not the numbers

import re
string = "E/Exception ['thisdevice:JFW32-000001007.IdName = telephonepole (null) has no hope, magic will be discard']"

final = re.sub(r'E.*?{14}', '', string)
print final

This pulls an exception which says its incorrect (I don't think i'm using it correctly)

I've tried to read the https://docs.python.org/2/library/re.html#re.sub and to be honest its confusing the hell out of me.. So i'm sorry for being a noob, but maybe if i get a working example in my case the pieces will fall together.

Kind Regards, Sym.

Upvotes: 0

Views: 51

Answers (2)

Veera Balla Deva
Veera Balla Deva

Reputation: 788

import re
string = "E/Exception ['thisdevice:JFW32-000001007.IdName = telephonepole (null) has no hope, magic will be discard']"

final = re.sub(r'J[\w\d]+\-[\d]+', '', string)
print final
>>>E/Exception ['thisdevice:.IdName = telephonepole (null) has no hope, magic will be discard']

Upvotes: 1

FlyingTeller
FlyingTeller

Reputation: 20590

How about

re.sub(r'J.{4}-.{9}', '', string)

matches 'J', followed by four characters, followed by '-', followed by 9 characters.

Upvotes: 1

Related Questions