WPF将Button
的content
中的单个下划线视为助记符
但是,内容很可能需要包含下划线。
内容是由用户定义的,没有什么可以阻止它们有多个下划线,无论是否顺序。如
This_Is It for the__moment and this is three___of the things
如果我将上面无意义的字符串赋值给Button。内容,它将把单个下划线作为助记符,并将产生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, "__");
下面的c#代码应该可以满足您的需求。
var reg = new Regex("(?<!_)_(?!_)");
reg.Replace("your string","__");
你可以做一个环顾检查
(?<!_)_(?!_)
并将下划线替换为双下划线
demo here: http://regex101.com/r/bD1cI9