【问题标题】:What is a clean way to parse multiple sections of a string in C#?在 C# 中解析字符串的多个部分的干净方法是什么?
【发布时间】:2012-05-10 20:19:14
【问题描述】:

我有一个可能包含 XML 和普通字符串的字符串。我需要为字符串中的所有实例解析出<math....</math>。如何从此字符串中解析出此字符串的多个部分(从<math> 到</math>)?

Here is some content <math
xmlns="http://www.w3.org/1998/Math/MathML">  
<mi>a</mi><mo>&#x2260;</mo><mn>0</mn> </math>, that is mixed in with
this other content <math xmlns="http://www.w3.org/1998/Math/MathML">  
<mi>a</mi><msup><mi>x</mi><mn>2</mn></msup>   <mo>+</mo>
<mi>b</mi><mi>x</mi>   <mo>+</mo> <mi>c</mi> <mo>=</mo> <mn>0</mn>
</math> we want to be able to seperate this string

背景: 我试图使这个问题通用。我正在尝试做的细节是针对 MVC3 编码与 Raw。默认情况下,它将对所有内容进行编码。我不希望它对 MathML 进行编码,但希望它对其他所有内容进行编码。所以我想将其中的一部分渲染为 Html.Raw(MathML 部分),其余部分我想渲染为正常编码的字符串。

【问题讨论】:

  • 你能改变这个数据的格式吗?通常很难以“干净”的方式解析有点不一致的数据格式。
  • 是的,这个数据的输入是一个字符串。我想我可以转换成任何我需要的东西来更好地帮助解析它。
  • 嗯,我的意思是字符串的格式。字符串很好,但在大多数情况下(正如您所发现的),将 XML 与非 xml 混合是一个坏主意。如果它是兼容的 XML,那么您可以简单地使用 .NET 的 XML 解析器。
  • @EdS。同意,但这确实让我想知道 MarkDown 是如何做到的。
  • 数据可以混合。只是我收到的方式,所以不能更改文件的源格式。

标签: c# string asp.net-mvc-3 encoding mathml


【解决方案1】:

如果您通常可以预期 XML 格式正确,或者至少格式一致,您应该能够使用 regular expressions 去除 XML。

您可以尝试使用Expresso 来制作您的表情。

如果你想解析你去掉的 XML,那是 .NET XMLParser 的工作。

【讨论】:

    【解决方案2】:

    我不是正则表达式爱好者,但这是我尝试过的,我得到了正确的结果。请以它为基础,并在必要时对其进行修改。

    我是从 Stackoverflow 上的 post 获得的。

    string yourstring = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">   <mi>a</mi><mo>&#x2260;</mo><mn>0</mn> </math>, that is mixed in with this other content <math xmlns=\"http://www.w3.org/1998/Math/MathML\">   <mi>a</mi><msup><mi>x</mi><mn>2</mn></msup>   <mo>+</mo> <mi>b</mi><mi>x</mi>   <mo>+</mo> <mi>c</mi> <mo>=</mo> <mn>0</mn> </math>";
    
    try
    {
         yourstring = Regex.Replace(yourstring, "(<math[^>]+>.+?</math>)", "");
    }
    catch (ArgumentException ex)
    {
         // Syntax error in the regular expression
    }
    

    得到的字符串是:

    , that is mixed in with this other content 
    

    【讨论】:

    • 这可行。让我玩一下,看看能不能搞定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多