0

重複の可能性:
.NET を使用して、2 つの (ブラケット) の間にあるテキストの文字列を抽出するにはどうすればよいですか?

括弧で囲まれた文字列の一部を削除するのを手伝ってくれる人はいますか?

たとえば、html/xml から解析された文字列があるため、次のように文字列にコメントが残ります。

"hello <!-- this is not meant to be here --> world, please help me"

を含むコメント全体を削除し、<!--, words, and -->「こんにちは世界、助けてください」のままにしたい

ありがとうございました!

4

3 に答える 3

4

正規表現を使用します。

 string x ="hello <!-- this is not meant to be here --> world, please help me";
 string y = Regex.Replace(x, "<!--.*?-->", "");
于 2012-07-11T10:21:14.793 に答える
1
string text = "hello <!-- this is not meant to be here --> world, please help me";

int start = text.IndexOf("<!--");
int end = text.IndexOf("-->") - "-->".Length;

string cleanText = text.Remove(start, end);
于 2012-07-11T10:26:35.527 に答える
0

正規表現を使用します。

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var regex = new Regex("[<][^<]*[>]"); // or "[<]!--[^<]*--[>]"
            var input = "hello <!-- this is not meant to be here --> world, please help me";
            var output = regex.Replace(input, String.Empty); // hello  world, please help me
        }
    }
}

この正規表現パターン - [<][^<]*[>]- は次を意味します。

  • 左角括弧 - [<]

  • 次に、開き角括弧ではない任意の数 (*) の文字 - [^<]

  • 最後に、閉じ角括弧 - [>]

regex.Replace(input, String.Empty);- これは、上記のパターンに一致するすべての部分文字列を空の文字列に置き換えることを意味します。

于 2012-07-11T10:20:08.753 に答える