【问题标题】:Remove characters from C# string not belonging to a specicif code page从 C# 字符串中删除不属于特定代码页的字符
【发布时间】:2015-05-02 12:04:43
【问题描述】:

在 C# 中,我有一个字符串继续使用代码页 37 US 插入到数据库表中。例如,'€' 将导致插入操作失败。

有什么好方法可以清理代码页 37 中未表示的字符串,并可以用一些默认字符替换这些字符?

【问题讨论】:

    标签: c# string codepages


    【解决方案1】:

    这样的?

            var euroString = "abc?€./*";
            var encoding37 = System.Text.Encoding.GetEncoding(
                37, 
                new EncoderReplacementFallback("_"), //replacement char
                new DecoderExceptionFallback());
            var byteArrayWithFallbackChars = encoding37.GetBytes(euroString);
            var utfStringFromBytesWithFallback = new string(encoding37.GetChars(byteArrayWithFallbackChars));
            //returns "abc?_./*"
    

    P.S.:您可以只使用 GetEncoding(37),但在这种情况下,替换字符是 ?,我认为这对于 DB 来说不太合适 :)

    【讨论】:

      【解决方案2】:

      这是一个将输入限制为允许字符范围的正则表达式:

      https://dotnetfiddle.net/WIrSSO

      const string Allowed = @"1-9\."; //Add allowed chars here
      string cleanStr = Regex.Replace("£1.11", "[^" + Allowed + "]", "");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 1970-01-01
        • 2019-11-09
        • 2021-01-25
        • 1970-01-01
        • 2015-10-02
        相关资源
        最近更新 更多