正则表达式以查找句子中的最后一个单词 [英] Regular expression to find last word in sentence

查看:439
本文介绍了正则表达式以查找句子中的最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用正则表达式找到句子中的最后一个单词?

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

推荐答案

如果你需要找到最后一个单词在一个字符串中,然后这样做:

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;

在此语句之后,$ 1将保留字符串中的最后一个单词。您可能需要通过添加更多标点符号来扩展字符类[。!?]。

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

在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];

?> 

这篇关于正则表达式以查找句子中的最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆