使用Regex C#获取最后一行 [英] Get last word in a line using Regex C#
本文介绍了使用Regex C#获取最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在一行中得到最后一句话。
有些行末尾有空白,有些可能没有。
我试过:
< pre lang =xml> \\\\ [^ A-zÀ-ú0-9] + $
但是这个回报以空格结尾的行的空间。
解决方案
但这会返回以空格结尾的行的空间。
我不知道你为什么需要正则表达式:
string lastWord = input.Split(' ')。Last();
正则表达式非常强大但在这种情况下它就像使用大锤破解坚果。在这种情况下(正如你所发现的)Regex的缺点是没有等价的StringSplitOptions.RemoveEmptyEntries尽管你可以使用类似
var匹配的东西= reg.Split(input).Where(s =>!String.IsNullOrEmpty(s));我个人更喜欢解决方案1中_dude_提出的方法,但修改后处理空字符串和其他异常因此:
string lastWord = input.Split(new char [] {''},
StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
I would like to get the last word in a line.
Some line has a blank at the end and some may not.
I have tried:
\\s[^A-zÀ-ú0-9]+$
But this return the space for the line which end with space.
解决方案
But this return the space for the line which end with space.
I don't know why do you need the regular expression:
string lastWord = input.Split(' ').Last();
Regex is very powerful but in this case it is like using a sledgehammer to crack a nut. The disadvantage of Regex in this case (as you have discovered) is that there is no equivalent ofStringSplitOptions.RemoveEmptyEntriesalthough you could use something like
var matches = reg.Split(input).Where(s => !String.IsNullOrEmpty(s));Personally I prefer the method proposed by _dude_ in Solution 1 but modified to handle empty strings and other anomalies thus:
string lastWord = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
这篇关于使用Regex C#获取最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文