简体   繁体   中英

RegEx for replacing special patterns in a list

I have been working on a python script to tweet some info about my pihole and have came across a small problem. I can't seem to get re.sub to work for me like I want it to.

What I am trying to accomplish is taking the output of netifaces.interfaces() which for me is ['lo', 'ens4', 'tun0', 'tun1'] and make it look like ens4, tun0, tun1

I have tried using

netfaces = str(netifaces.interfaces())
netfaces = re.sub('\[|\'|lo|\'|\]', '', netfaces)

but it gives me this output:

, ens4, tun0, tun1 

edit:

thanks @the-fourth-bird

i expanded on the regex they gave and came to this

regex test

'lo'(?:,\\s*)?|[][')(]|(?:,\\s*)?'lo'

my take:

'lo'(?:,\\s*)? - searches the string for 'lo', and removes no matter were found

[][')(] - removes all ][ ' )( no matter were found

(?:,\\s*)?'lo' - removes all , 'lo' no matter were found

which also works for the os.getloadavg() output that i'm getting as well

It is not clear why you generated that string which looks like a list, but you can use this regex,

^[^,]+,\s*|'|\]

and remove it with empty string to get your desired string.

As you only want to remove first comma and everything before it, you need ^[^,]+,\\s* and rest you need to also remove all quotes using ' and ] with \\]

Regex Demo

As an alternative way, where I assume you originally had your elements in a list, you should preferable use this approach which doesn't depend upon regex to get your intended output.

arr = ['lo', 'ens4', 'tun0', 'tun1']
arr.remove('lo')
print(', '.join(arr))

Prints your intended output,

ens4, tun0, tun1

The reason you get that result is that you are matching 4 alternations which you might also write as [][']|lo but you are not matching the comma and the space after it so that will not be removed.

If you want to remove 'lo' from the list without leaving a comma and space at the start, you could use:

'lo'(?:,\s*)?|[][']
  • 'lo'(?:,\\s*)? Match lo followed by an optional part to match a comma and 1+ whitespace characters
  • | Or
  • []['] Match any of the listed in the character class [ , ] , '

Replace with an empty string.

Regex demo | Python demo

For example

import re
regex = r"'lo'(?:,\s*)?|[][']"
test_str = "['lo', 'ens4', 'tun0', 'tun1']"
result = re.sub(regex, "", test_str)

if result:
    print (result)

Result

ens4, tun0, tun1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM