同様の問題がありました。私はきれいな URL が欲しかったので、URL には文字、数字、および _ のみを許可する必要があるという結論に達しました。
それは問題ありませんが、良い正規表現を書いたところ、すべての UTF-8 文字が .NET の文字ではないことを認識し、うまくいかないことに気付きました。これは、.NET 正規表現エンジンの既知の問題のようです。だから私はこの解決策にたどり着きました:
private static string GetTitleForUrlDisplay(string title)
{
if (!string.IsNullOrEmpty(title))
{
return Regex.Replace(Regex.Replace(title, @"[^A-Za-z0-9_-]", new MatchEvaluator(CharacterTester)).Replace(' ', '-').TrimStart('-').TrimEnd('-'), "[-]+", "-").ToLower();
}
return string.Empty;
}
/// <summary>
/// All characters that do not match the patter, will get to this method, i.e. useful for Unicode characters, because
/// .NET implementation of regex do not handle Unicode characters. So we use char.IsLetterOrDigit() which works nicely and we
/// return what we approve and return - for everything else.
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string CharacterTester(Match m)
{
string x = m.ToString();
if (x.Length > 0 && char.IsLetterOrDigit(x[0]))
{
return x.ToLower();
}
else
{
return "-";
}
}