C# 从c中的字符串中提取最后一个匹配项#
我的字符串格式为C# 从c中的字符串中提取最后一个匹配项#,c#,.net,regex,lookaround,capture-group,C#,.net,Regex,Lookaround,Capture Group,我的字符串格式为[abc].[其他字符串].[can.allow.contain.periods].[我们的匹配] 我现在想匹配字符串“我们的比赛”(即没有括号),所以我玩了lookarounds之类的东西。我现在得到了正确的匹配,但我不认为这是一个干净的解决方案 (?<=\.?\[) starts with '[' or '.[' ([^\[]*) our match, i couldn't find a way to not use a negated charact
[abc].[其他字符串].[can.allow.contain.periods].[我们的匹配]
我现在想匹配字符串“我们的比赛”(即没有括号),所以我玩了lookarounds之类的东西。我现在得到了正确的匹配,但我不认为这是一个干净的解决方案
(?<=\.?\[) starts with '[' or '.['
([^\[]*) our match, i couldn't find a way to not use a negated character group
`.*?` non-greedy did not work as expected with lookarounds,
it would still match from the first match
(matches might contain escaped brackets)
(?=\]$) string ends with an ]
(?带String.Split():
您在拆分的[7]中得到“out match”,并且can.allow.contain.periods作为一个字符串保留(拆分的[4])
编辑:数组将在[]内包含字符串,然后。依此类推,因此如果组数可变,则可以使用该字符串获取所需的值(或删除仅为“.”的字符串)
编辑以将反斜杠添加到分隔符中,以处理类似“\[abc\]”的情况
Edit2:对于嵌套[],请执行以下操作:
string input = @"[abc].[some other string].[can.also.contain.periods].[our [the] match]";
string[] seps2 = { "].["};
string[] splitted = input.Split(seps2, StringSplitOptions.RemoveEmptyEntries);
您需要在最后一个元素(索引3)中删除我们的[the]match],并且必须删除额外的]您有几个选项:
- -是的,.NET正则表达式可以做到这一点!使用它
- 用贪婪前缀匹配整个事物,用括号捕捉你感兴趣的后缀
- 所以一般来说,
模式
变成了*(模式)
- 在本例中,
*\[([^\]]*)\]
,然后提取\1
捕获的内容()
工具书类
假设您可以保证输入格式,并且它只是您想要的最后一个条目,则可以使用LastIndexOf
:
string input = "[abc].[some other string].[can.also.contain.periods].[our match]";
int lastBracket = input.LastIndexOf("[");
string result = input.Substring(lastBracket + 1, input.Length - lastBracket - 2);
假设字符串在最后一场比赛结束后结束,那么下面的步骤就可以了
string input = "[abc].[some other string].[can.also.contain.periods].[our match]";
var search = new Regex("\\.\\[(.*?)\\]$", RegexOptions.RightToLeft);
string ourMatch = search.Match(input).Groups[1]);
在最后一个元素中使用转义括号是否有效?@knittl:编辑了答案。如果您在分隔符中添加反斜杠,它将在相同索引处返回干净的值,如果您的意思类似“\[abc\]”,我的意思是[…].[…]。[这是\[the\]last value]
,那么我想“这是\[the\]last value”
@knittl:添加了代码-我用“].[”将其拆分,因为内括号中没有。现在拆分返回整个值。好的,这基本上就是我的Regex.split(…).Last().TrimEnd(“]”);
但是我认为我对string.split仍然有一些误解
string input = "[abc].[some other string].[can.also.contain.periods].[our match]";
var search = new Regex("\\.\\[(.*?)\\]$", RegexOptions.RightToLeft);
string ourMatch = search.Match(input).Groups[1]);