1

我想得到两个字符串。行中的最后一个词(在下面有效),然后是最后一个词,我想用正则表达式来做到这一点。有人建议我使用^(.*?)\b\w+$作为模式并使用$1作为匹配项(但我不知道如何在 .NET 中完成)

    Dim s As String = "   Now is the time for all good men to come to the aid of their country    "
    s = Regex.Replace(s, "^[ \s]+|[ \s]+$", "")  'Trim whitespace
    Dim lastword As String = Regex.Match(s, "\w*$", RegexOptions.None).ToString
    Debug.Print(lastword)

    Dim therest As String = Regex.Match(s,......)
4

2 回答 2

4

我知道你写过你“想用正则表达式来做这件事”,但是因为没有正则表达式的解决方案要容易得多,可读性要强得多,而且不太可能包含隐藏的错误,我还是敢建议:

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 ;-)
于 2013-05-10T14:27:35.387 回答
2

您的模式应该可以工作,并且您正在寻找的是匹配集合的第一个捕获:

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
于 2013-05-10T14:26:31.033 回答