WPF把一个下划线作为记忆中content
的Button
但是,内容可能需要包含下划线。
内容是由用户定义的,没有什么可以阻止它们具有多个下划线的,无论是否顺序地。例如
This_Is It for the__moment and this is three___of the things
如果我将上述无用的字符串分配给Button.Content,它将把下划线视为助记符,并会导致ThisIs It for the__moment and this is three___of the things
(请注意_丢失了,我现在将ThisIs作为一个单词)。我想要它对其进行更新This__Is It for the__moment and this is three___of the things
(请注意,它现在是双下划线,但是其他下划线的出现保持不变)。
这就是我所拥有的,它是如此笨拙(尽管可以使用)。
static void Main(string[] args)
{
Console.WriteLine(Other("This_Is It for the__moment and this is three___of the things"));
Console.ReadKey(); // result is This__Is It for the__moment and this is three___of the things (note the double __ after the first word This)
}
static string Other(string content)
{
List<int> insertPoints = new List<int>();
for (int i = 0; i < content.Length; i++)
{
char current = content[i];
if (content[i] == '_' && content[i + 1] != '_')
{
if (i - 1 >= 0)
if (content[i - 1] == '_')
continue;
insertPoints.Add(i);
}
}
foreach (var item in insertPoints)
{
content = content.Insert(item, "_");
}
return content;
}
我的问题是,使用RegEx编写的代码会更少吗?
您可以使用以下正则表达式查找单个下划线:
(?<!_)_(?!_)
然后将其替换为两个下划线。
(?<!_)
是一个负面的回头路;它可以防止匹配的下划线在另一个下划线之前出现。
(?!_)
是负面的前瞻;它可以防止匹配的下划线后面跟着另一个下划线。
您将需要使用,using System.Text.RegularExpressions;
并且可以像下面这样使用它:
var regex = new Regex(@"(?<!_)_(?!_)");
var result = regex.Replace(str, "__");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句