jellyfin-server/Emby.Server.Core/Localization/TextLocalizer.cs

57 lines
1.8 KiB
C#
Raw Normal View History

2016-11-05 02:17:18 +00:00
using System;
using System.Globalization;
using System.Linq;
using System.Text;
2016-11-29 19:13:01 +00:00
using System.Text.RegularExpressions;
2016-11-05 02:17:18 +00:00
using Emby.Server.Implementations.Localization;
2016-11-11 07:24:36 +00:00
namespace Emby.Server.Core.Localization
2016-11-05 02:17:18 +00:00
{
public class TextLocalizer : ITextLocalizer
{
public string RemoveDiacritics(string text)
{
2016-11-29 19:13:01 +00:00
if (text == null)
{
throw new ArgumentNullException("text");
}
var chars = Normalize(text, NormalizationForm.FormD)
.Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) != UnicodeCategory.NonSpacingMark);
return Normalize(String.Concat(chars), NormalizationForm.FormC);
}
private static string Normalize(string text, NormalizationForm form, bool stripStringOnFailure = true)
{
if (stripStringOnFailure)
{
try
{
return text.Normalize(form);
}
catch (ArgumentException)
{
// will throw if input contains invalid unicode chars
// https://mnaoumov.wordpress.com/2014/06/14/stripping-invalid-characters-from-utf-16-strings/
text = StripInvalidUnicodeCharacters(text);
return Normalize(text, form, false);
}
}
return text.Normalize(form);
}
private static string StripInvalidUnicodeCharacters(string str)
{
var invalidCharactersRegex = new Regex("([\ud800-\udbff](?![\udc00-\udfff]))|((?<![\ud800-\udbff])[\udc00-\udfff])");
return invalidCharactersRegex.Replace(str, "");
2016-11-05 02:17:18 +00:00
}
public string NormalizeFormKD(string text)
{
return text.Normalize(NormalizationForm.FormKD);
}
}
}