felix001
felix001

Reputation: 16741

Python RegEx Matching

I have a string that I want to pull a substring from. Currently I'm using 3 lines to achieve this as follows:

for z in my_list:
    abc = re.sub('\n', '', z[0])
    xyz = re.sub('SNMPv2-SMI::', '', abc)
    egg = re.sub('\..*\ =.*$', '', xyz)

However, as this is using 3 separate regex commands, is there a way to get the string using a single statement/command?

Upvotes: 2

Views: 107

Answers (4)

Zulu
Zulu

Reputation: 9285


You can use silce tips for delete the fisrt character :

  z[1:]

And like the others say you can make a logical OR with '(a|b|c)'. I think your code like that :

for z in my_list:
    egg = re.sub( r'(SNMPv2-SMI::|\..*\ =.*)', '', z[1:] )

Upvotes: 0

tuxuday
tuxuday

Reputation: 3037

as the replacement string is same you can use |.

>>> import re
>>> s="this is for testing"
>>> re.sub("this|for|test","REPLACED",s)
'REPLACED is REPLACED REPLACEDing'

Upvotes: 2

georg
georg

Reputation: 215039

Just use the | ("or") operator:

strng = re.sub(r'(this)|(that)|(something else)', '', strng)

Upvotes: 2

Arnab Datta
Arnab Datta

Reputation: 5256

for z in my_list:
    abc = re.sub('\..*\ =.*$', '', re.sub('SNMPv2-SMI::', '', re.sub('\n', '', z[0]))) 

Ugly little one-liner for you

Upvotes: 0

Related Questions