我想得到两个字符串。该行的最后一个单词(在下面工作)然后是最后一个单词的所有内容,我想用正则表达式做这个。有人建议我使用 ^(。*?)\ 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,......)
答案 0 :(得分: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 ;-)
答案 1 :(得分: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