Python re.search() and re.findall() [duplicate]

2019-07-24 00:27发布

This question already has an answer here:

I am trying to solve this from problem from Hackerrank. It is a Machine Learning problem. Initially, I tried to read all the words from the Corpus file for building unigram frequencies. According to this ML problem word is defined as

Word is a sequence of characters containing only letters from a to z (lowercase only) and can contain hyphens (-) and apostrophe ('). Word should begin and end with lowercase letters only.

I wrote a regular expression in python like this:

pat = "[a-z]+( ['-]+[a-z]+ ){0,}"

I tried using both re.search() and re.findall(). I have problems in both.

  • Problem with re.findall():

    string = "HELLO W-O-R-L-D"
    

    output of re.findall():

    [('Hello', ''), ('W', '-D')]
    

    I couldn't get the word W-O-R-L-D. While using re.search(), I was able to get it correctly

  • Problem with re.search():

    string = "123hello456world789"
    

    output of re.search():

    'hello'
    

    In this case, when using re.findall(), I could get both 'hello' and 'world'.

1条回答
做个烂人
2楼-- · 2019-07-24 01:09

As I posted on your previous question you should use re.findall() - but regardless, your problem is that your regex is wrong. See the below example:

>>> import re
>>> regex = re.compile(r'([a-z][a-z-\']+[a-z])')
>>> regex.findall("HELLO W-O-R-L-D") # this has uppercase
[]  # there are no results here, because the string is uppercase
>>> regex.findall("HELLO W-O-R-L-D".lower()) # lets lowercase
['hello', 'w-o-r-l-d'] # now we have results
>>> regex.findall("123hello456world789")
['hello', 'world']

As you can see, the reason why you were failing on the first sample you provided is because of the uppercase, you can simply add the re.IGNORECASE flag, though you mentioned that matches should be lowercase only.

查看更多
登录 后发表回答