简体   繁体   中英

Python For-Loop with Regex

blank blank blank blank blank blank

The Issue

Your test to see if re.findall has returned the value you want is bugged. Your check:

if test != None:

Will always be true, and you'll always append whatever value word holds to wkar . From the re docs (assuming python3, but the behavior doesn't change):

re.findall( pattern, string, flags=0 )

Return all non-overlapping matches of pattern in string, as a list of strings... Empty matches are included in the result .

(emphasis mine)

An empty list is not None , that's wkar holds all the values in your sentence. (Interestingly, this is the exact opposite of the behavior you mentioned at the beginning of your question.)

The Solution

Don't use a regex, it's the wrong tool for this job. This can be solved using builtin functions. Additionally, you're taking a performance hit for something that can just be done in an if statement

# use the builtin split function to split sentence on spaces
sentence = sentence.split(" ")

wkar = []

# iterate over each word...
for word in sentence:
    #...and see if it matches the test word
    if word == 'text':
    wkar.append(word)

The re.findall() function does loop over the entire sentence. you don't have to do that part yourself. all you have to do to have the output you want is to do the following:

import re

sentence = 'This is some Text, then some more text with some Numbers 1357,  and even more text 357, the end.'

wkar = re.findall(r'text', sentence)

that will result in:

['text', 'text']

and if you want re.findall() to be case-insensitive use:

wkar = re.findall(r'text', sentence, flags=re.IGNORECASE)

that will give:

['Text', 'text', 'text']

Also in the future if you want to test regular expressions i suggest you use the great https://regex101.com/ website (make sure to chose the python button for the python regex string format).

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