.net 除了一行的最后一个字,你怎么能把所有的字都匹配起来呢?

.net 除了一行的最后一个字,你怎么能把所有的字都匹配起来呢?,.net,regex,vb.net,.net,Regex,Vb.net,我想要两条线。行中的最后一个字(在下面工作),然后是除最后一个字以外的所有字,我想用正则表达式来实现这一点。有人建议我使用^(.*?\b\w+$作为模式,并使用$1作为匹配(但我不知道如何在.NET中实现) 您的模式应该可以工作,您需要的是匹配集合的第一个捕获: Dim pattern As String = "^(.*?)\b\w+$" ' Use TrimEnd instead of regex replace (i.e. we don't nuke ant piles) Dim matc

我想要两条线。行中的最后一个字(在下面工作),然后是除最后一个字以外的所有字,我想用正则表达式来实现这一点。有人建议我使用^(.*?\b\w+$作为模式,并使用$1作为匹配(但我不知道如何在.NET中实现)


您的模式应该可以工作,您需要的是匹配集合的第一个捕获:

Dim pattern As String = "^(.*?)\b\w+$"

' Use TrimEnd instead of regex replace (i.e. we don't nuke ant piles)
Dim match As Match = Regex.Match(input.TrimEnd(), pattern)

If match.Success Then
    ' It will be the 0th capture on the 1st group
    Dim allButTheLast As String = match.Groups(1).Captures(0)
    ' Group 0 is the entire input which matched
End If

您的模式应该可以工作,您需要的是匹配集合的第一个捕获:

Dim pattern As String = "^(.*?)\b\w+$"

' Use TrimEnd instead of regex replace (i.e. we don't nuke ant piles)
Dim match As Match = Regex.Match(input.TrimEnd(), pattern)

If match.Success Then
    ' It will be the 0th capture on the 1st group
    Dim allButTheLast As String = match.Groups(1).Captures(0)
    ' Group 0 is the entire input which matched
End If
我知道你曾写过“想用regex实现这一点”,但由于没有regex的解决方案更简单、可读性更高,也不太可能包含隐藏的bug,我还是大胆地建议:

Dim s As String = "   Now is the time for all good men to come to the aid of their country    "
s = Trim(s)
Dim lastword = s.Split().Last()
Dim therest = Left(s, Len(s) - Len(lastword))
备选方案:

Dim therest = Left(s, s.LastIndexOf(" "))
Dim therest = s.Substring(0, s.LastIndexOf(" "))   ' Thanks to sixlettervariables
Dim therest = String.Join(" ", s.Split().Reverse().Skip(1).Reverse())   ' for LINQ fanatics ;-)
我知道你曾写过“想用regex实现这一点”,但由于没有regex的解决方案更简单、可读性更高,也不太可能包含隐藏的bug,我还是大胆地建议:

Dim s As String = "   Now is the time for all good men to come to the aid of their country    "
s = Trim(s)
Dim lastword = s.Split().Last()
Dim therest = Left(s, Len(s) - Len(lastword))
备选方案:

Dim therest = Left(s, s.LastIndexOf(" "))
Dim therest = s.Substring(0, s.LastIndexOf(" "))   ' Thanks to sixlettervariables
Dim therest = String.Join(" ", s.Split().Reverse().Skip(1).Reverse())   ' for LINQ fanatics ;-)

因此,删除最后一个单词和模式匹配,与剩下的匹配。为什么要这样修剪?请尝试“^\s+|\s+$”。NET Trim()将更简单、更高效。因此,请删除最后一个单词和模式匹配项,并将其与剩下的内容进行匹配。为什么要这样修剪?请尝试“^\s+|\s+$”。和.NET Trim()将更简单、更有效。修剪后,
input.Substring(input.LastIndexOf('')
for
lastWord
?@sixlettVariables:谢谢,很好的选择!修剪后,
input.Substring(input.LastIndexOf('')
lastWord
?@sixlettvariables:谢谢,很好的选择!效果很好。但是你能详细解释一下为什么我要用TrimEnd来代替吗?@WhiskerBiscuit:正则表达式就像在你的代码中运行另一个应用程序一样。
String
上的内在方法非常简单。每当你选择使用正则表达式时,你都应该问自己“为什么?”它们在合适的时候很好,在不合适的时候很糟糕。但是你能详细解释一下为什么我要用TrimEnd来代替吗?@WhiskerBiscuit:正则表达式就像在你的代码中运行另一个应用程序一样。
String
上的内在方法非常简单。每当你选择使用正则表达式时,你都应该问自己“为什么?”它们在合适的时候很好,在不合适的时候很糟糕。