首页 > 解决方案 > 正则表达式在线查找最后一个单词(包括符号)

问题描述

我正在努力寻找一行的最后一个词。这个词可能包括像 !@#$%^&*[] 等符号。这需要适用于 unicode 字符集。

正则表达式需要返回两组(都忽略行尾的任何空白)

这是我迄今为止尝试过(.*\b(\w+))\W*$的,但它不适用于单词中的符号。

'this test' => 'this test' and 'test'
' this test ' => 'this test' and 'test'
'this test$' => 'this test$' and 'test$'
'this# test$  ' => 'this# test$' and 'test$'

标签: .netregex

解决方案


对于非正则表达式选项,我们可以尝试仅在空间上拆分输入字符串,然后取最后一个条目:

string input = "this# test$";
string[] parts = input.Split(null);
string last = parts[parts.Length - 1];
Console.WriteLine(last)

这打印:

test$

如果您想要正则表达式方法,请尝试匹配以下模式:

\S+$

这将捕获在输入结束之前出现的所有连续的非空白字符。


推荐阅读