[英]Regex to get anything after last space in a string
我有一个字符串,里面有一堆单词,我想要的只是最后一个单词。 什么是正则表达式?
例如:
This is some sample words to work with
我只是想with
从上面的字符串。
一个更简单的解决方案是使用Split
方法:
string text = "This is some sample text to work with";
string last = text.Split(' ').Last();
我会使用LastIndexOf
,应该表现更好。
string text = "This is some sample words to work with";
string last = text.Substring(text.LastIndexOf(' '));
当然,如果文本有可能没有任何空格,您必须确保您没有尝试从 -1 索引中提取子字符串。
我猜你的需要虽然有点晚了,但这应该有效:
将 "[a-zA-Z]+$" 替换为 "[\\S]+$" => 将采用所有非空格字符。
如果您坚持使用正则表达式,那么以下内容将对您有所帮助
/[a-zA-Z]+$/
例子
Match m = Regex.Matches("This is some sample words to work with", "[a-zA-Z]+$")[0];
Console.WriteLine(m.Value);
=> with
根据原始问题(最后没有数字)获得“with”:
[^\W]+$
Regex.Match("This is some sample words to work with", @"[^\W]+$").Value == "with"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.