lasingallday
lasingallday

Reputation: 63

How to get string if substring match at beginning or middle, in Python's re?

import re
fileList = 
['notamatch','RC_test_CN_SK','test_SLU','test_CO','test_UL','SC_test_SRV']
for file in fileList:
    re.findall('\w+test\w+',file)
for file in fileList:
    re.findall('\Atest\w+',file)

The first for loop prints 'RC_test_CN_SK', and 'SC_test_SRV'. The second for loop prints 'test_SLU','test_CO', and 'test_UL'.

How do I do one re.findall search and get the five files I want?

Upvotes: 1

Views: 398

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

Test if your values start with 0+ word chars from the beginning of the string and then contain test:

import re
fileList = ['notamatch','RC_test_CN_SK','test_SLU','test_CO','test_UL','SC_test_SRV']
for file in fileList:
    if re.search(r'^\w*test', file):
        print(file)
# => ['RC_test_CN_SK','test_SLU','test_CO','test_UL','SC_test_SRV']

See the Python demo

Upvotes: 1

Thijs van Ede
Thijs van Ede

Reputation: 88

You can perform multiple searches using the regex or operator | in your example, you can perform the following loop:

for file in fileList:
    re.findall('\w+test\w+|\Atest\w+',file)

This query will match if either \w+test\w+ or \Atest\w+ is found.

Upvotes: 0

Related Questions