【问题标题】:How to convert superscript characters to normal text in C# string如何将上标字符转换为 C# 字符串中的普通文本
【发布时间】:2020-07-30 07:11:41
【问题描述】:

我有带有数学表达式的字符串,例如2⁻¹² + 3³ / 4⁽³⁻¹⁾

我想把这些字符串转换成2^-12 + 3^3 / 4^(3-1)的形式。

到目前为止,我可以提取上标数字并添加 ^

以下代码:https://dotnetfiddle.net/1G9ewP

using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    private static string ConvertSuperscriptToText(Match m){
        string res = m.Groups[1].Value;
            
        res = "^" + res;
        return res;
    }
    public static void Main()
    {
        string expression = "2⁻¹² + 3³ / 4⁽³⁻¹⁾";
        string desiredResult = "2^-12 + 3^3 / 4^(3-1)";
        
        string supChars = "([¹²³⁴⁵⁶⁷⁸⁹⁰⁺⁻⁽⁾]+)";
        string result = Regex.Replace(expression, supChars, ConvertSuperscriptToText);

        Console.WriteLine(result); // Currently prints 2^⁻¹² + 3^³ / 4^⁽³⁻¹⁾
        Console.WriteLine(result == desiredResult); // Currently prints false
    }
}

如何替换上标字符而不一一替换?

如果我必须一个一个地替换它们,我如何使用类似于 PHP 的 str_replace 的集合来替换它们,它接受数组作为搜索和替换参数?

额外问题,如何将各种上标字符替换为普通文本并返回上标?

【问题讨论】:

  • 我认为res = "^" + res.Normalize(NormalizationForm.FormKD); 应该可以解决问题。见:How to convert super- or subscript to normal text in C#
  • @AhmedAbdelhameed 减号有点不同,但除此之外效果很好。
  • 应该注意\p{No}会匹配任何上标、下标或非0-9的数字。不幸的是,上标没有任何意义,但是如果您知道自己没有任何其他字符,则可以使用它而不是列出上标数字。您仍然需要列出上标加号、减号和括号 @"([\p{No}⁽⁾⁻⁺]+)"
  • @AhmedAbdelhameed 这看起来非常优雅。除了juharr提到的减号外,效果很好。不幸的是,减号对于整个 shebang 非常重要 ;-)。
  • @juharr 我已经尝试了@"([\p{No}⁽⁾⁻⁺]+)",但找不到如何替换它,所以它又重新列出了它们。我喜欢 AhmedAbdelhameed 的解决方案,我可能会在进一步的清理过程中与最后清理减号配对。

标签: c# regexp-replace


【解决方案1】:

您只需要一个字典来映射这些值,然后您可以使用 Linq 将它们翻译过来并从中创建一个新字符串。

private static Dictionary<char, char> scriptMapping = new Dictionary<char, char>()
{
    ['¹'] = '1',
    ['²'] = '2',
    ['³'] = '3',
    ['⁴'] = '4',
    ['⁵'] = '5',
    ['⁶'] = '6',
    ['⁷'] = '7',
    ['⁸'] = '8',
    ['⁹'] = '9',
    ['⁰'] = '0',
    ['⁺'] = '+',
    ['⁻'] = '-',
    ['⁽'] = '(',
    ['⁾'] = ')',
};

private static string ConvertSuperscriptToText(Match m){
    string res = m.Groups[1].Value;

    res = "^" + new string(res.Select(c => scriptMapping[c]).ToArray());
    return res;
}

您还可以从字典中创建您的正则表达式,这样只有一个地方可以添加新的下标。

string supChars = "([" + new string(scriptMapping.Keys.ToArray()) + "]+)"

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多