oz123
oz123

Reputation: 28878

match a substring in a list of substrings

There is a better way to do with with regex,

>>> HOSTS=['backup-ros', 'backupa-files', 'print-server1','print-server2'] 
>>> for host in HOSTS:
      ...     if 'backup' in host: 
... 
backup-ros 
backupa-files

which is partially correct.

I tried this:

a=re.findall(r'backup-(\w+)', ' '.join(HOSTS))
>>> a
['ros']

which gave me 'ros'.

And finally:

a=re.match(r'backup-(\w+)', ' '.join(HOSTS))
>>> a.group()
'backup-ros' 

Which I think is correct. However, I still wanted to ask if this is the right way the better way to do it.

EDIT: I realized after a few comments, that it's not clear what I'm looking for. I needed to find the names of directories called "backup-somename" inside a directory. But I didn't want to include the directories who's name is for example "backupa-somename" or "backupb-somename". That is why my first for loop was not good enough for me.

Thanks, in advance. Oz

Upvotes: 1

Views: 151

Answers (2)

karora
karora

Reputation: 238

Instead of this

a=re.findall(r'backup-(\w+)', ' '.join(HOSTS)) 

use

a=re.findall(r'(backup-[\w]+)', ' '.join(HOSTS)).

The issue was your regex was matching whole pattern but was grouping \w+ at the end. This is a simpler way

Upvotes: 0

tito
tito

Reputation: 13271

Without regex, could you consider .startswith() ?

>>> HOSTS = ['backup-ros', 'backupa-files', 'print-server1','print-server2']
>>> backups = [x for x in HOSTS if x.startswith('backup-')]
>>> backups
['backup-ros']

No need to join the list into a string.

Upvotes: 4

Related Questions