How can I remove accelerator characters from a string?

孤街醉人 提交于 2019-12-04 14:47:21

I've edited (removed) my previous answer. I think the simplest way would be this regular expression:

string input = "s&trings && stuf&f &";
input = Regex.Replace(input, "&(.)", "$1");

That correctly handles repeated ampersands as well as the case where the ampersand is the last character.

EDIT, based on additional provided information:

So the WinForms expression would be "&(.?)", and the WPF expression would be "_(.)". You ask for a solution that addresses both cases, but I'm not sure what you're asking. Your original question said that the code knows whether it's processing WPF format or WinForms format. So I would envision a method:

string StripAccelerators(string s, bool isWinForms)
{
    string pat = (isWinForms) ? "&(.?)" : "_(.)";
    return Regex.Replace(s, pat, "$1");
}

And, yes, I realize that using a Boolean flag in the interface is less than ideal. Ideally, you'd use an enumerated type, or perhaps have two separate methods.

I don't think you want to have a single regular expression that will perform both. It's possible, but then you'll end up removing underlines from WinForms strings, or ampersands from WPF strings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!