Simple Python Regex Find pattern

后端 未结 5 769
梦谈多话
梦谈多话 2020-12-29 10:41

I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the li

相关标签:
5条回答
  • 2020-12-29 11:16
    >>> sentence="a quick brown fox for you"
    >>> pattern="fo"
    >>> for word in sentence.split():
    ...     if word.startswith(pattern):
    ...         print word
    ...
    fox
    for
    

    Split the sentence on spaces, use a loop to search for the pattern and print them out.

    0 讨论(0)
  • 2020-12-29 11:21
    import re
    
    s = "Your sentence that contains the word ROAD"
    s = re.sub(r'\bROAD', 'RD.', s)
    
    print s
    

    Read: http://diveintopython3.org/regular-expressions.html

    0 讨论(0)
  • 2020-12-29 11:24

    I second the Dive Into Python recommendation. But it's basically:

    m = re.findall(r'\bf.*?\b', 'a fast and friendly dog')
    print(m)
    

    \b means word boundary, and .*? ensures we store the whole word, but back off to avoid going too far (technically, ? is called a lazy operator).

    0 讨论(0)
  • 2020-12-29 11:28
    import re
    print re.findall(r'\bv\w+', thesentence)
    

    will print every word in the sentence that starts with 'v', for example.

    Using the split method of strings, as another answer suggests, would not identify words, but space-separated chunks that may include punctuation. This re-based solution does identify words (letters and digits, net of punctuation).

    0 讨论(0)
  • You could do (doesn't use re though):

    matching_words = [x for x in sentence.split() if x.startswith(CHAR_TO_FIND)]
    

    Regular expressions work too (see the other answers) but I think this solution will be a little more readable, and as a beginner learning Python, you'll find list comprehensions (like the solution above) important to gain a comfort level with.

    0 讨论(0)
提交回复
热议问题