我有这样的文字:
((#) This is text
((#) This is subtext
((#) This is sub-subtext #)
#)
#)
我制作了以下正则表达式:
var counter = 0;
return Regex.Replace(text,
@"\(\(#\)(.*?)#\)",
m =>
{
var str = m.ToString();
counter++;
return counter + ") " + str.Replace("((#)", "").Replace("#)", "")
});
所以我期望的结果是这样的
1) This is text
2) This is subtext
3) This is sub-subtext
我知道这不会正常工作,因为正则表达式将从第二个 ((#) 等开始使用 #)。
如何避免这种冲突?谢谢! :)
最佳答案
这是我建议的解决方案:
- 使用具有平衡组的正则表达式获取嵌套字符串,
- 替换循环中的子字符串。
参见 the regex demo here .它匹配空字符串,但也捕获所有以 ((#)
开头并以 #)
结尾的嵌套子字符串。
这是 C# 演示代码:
var text = @"((#) This is text
((#) This is subtext
((#) This is sub-subtext #)
#)
#)";
var chunks = Regex.Matches(text,
@"(?s)(?=(\(\(#\)(?>(?!\(\(#\)|#\)).|\(\(#\)(?<D>)|#\)(?<-D>))*(?(D)(?!))#\)))")
.Cast<Match>().Select(p => p.Groups[1].Value)
.ToList();
for (var i = 0; i < chunks.Count; i++)
text = text.Replace(chunks[i], string.Format("{0}) {1}", (i+1),
chunks[i].Substring(4, chunks[i].Length-6).Trim()));
请注意 .Substring(4, chunks[i].Length-6)
只是从 ((#)
到 #)
。由于我们知道分隔符,我们可以对这些值进行硬编码。
输出:
要了解有关平衡组的更多信息,请参阅 Balancing Groups Definition和 Fun With .NET Regex Balancing Groups .
关于c# - 嵌套模式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34308354/