Regular expression to find last word in sentence

前端 未结 2 653
一向
一向 2020-12-17 21:51

How can I find last word in a sentence with a regular expression?

2条回答
  •  庸人自扰
    2020-12-17 22:05

    If you need to find the last word in a string, then do this:

    m/
        (\w+)      (?# Match a word, store its value into pattern memory)
    
        [.!?]?     (?# Some strings might hold a sentence. If so, this)
                   (?# component will match zero or one punctuation)
                   (?# characters)
    
        \s*        (?# Match trailing whitespace using the * because there)
                   (?# might not be any)
    
        $          (?# Anchor the match to the end of the string)
    /x;
    

    After this statement, $1 will hold the last word in the string. You may need to expand the character class, [.!?], by adding more punctuation.

    in PHP:

     
    

提交回复
热议问题