Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
540 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:

<?php

$str = 'MiloCold is Neat';
$str_Pattern = '/[^ ]*$/';

preg_match($str_Pattern, $str, $results);

// Prints "Neat", but you can just assign it to a variable.
print $results[0];

?> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...