3

私の入力テキストは次のとおりです。

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">2</string>

上記の入力から数値を抽出するために使用する正規表現パターンは何ですか?

var pattern = "<string ?>?</string>"; // how to write this?
var match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);

ありがとう、

4

4 に答える 4

5

このパターンはうまくいくはずです:

"<string[^>]+>([0-9]+)</string>"

壊す:

<string   - Match the string <string
[^>]+     - Followed by one or more characters that are not >
>         - Followed by >
(         - Start capturing group
[0-9]+    - Followed by one or more of the digits 0-9
)         - End capturing group
</string> - Followed by the string </string>

例が文字列全体である場合は、最初と最後にそれぞれ and を^使用して固定することができます。$

.NETではどの Unicode 数字にも一致するため、 では[0-9]なく andを使用していることに注意してください。\d\d

于 2012-12-13T11:13:40.507 に答える
2

LinqToXml を使用した別のアプローチ:

var ele = XElement.Parse("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">2</string>");
var valueString = ele.Value; //valueString = "2";

アップデート

正規表現の場合: @Oded のソリューションを(?<=startRegex)and (?=endRegex)(後読みと先読み) で拡張するので、不必要な<string>タグは一致値で省略されます。

(?<=<string[^>]+>)([0-9]+)(?=</string>)
于 2012-12-13T11:41:05.493 に答える
1

これは、正規表現以外の方法です。

string str = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">2</string>";
int startIndex = str.IndexOf('>');
int endIndex = str.LastIndexOf('<');
int numberLenght =  (endIndex - startIndex) - 1;
string result = str.Substring(startIndex + 1, numberLenght);
于 2012-12-13T11:19:19.007 に答える
1

このメソッドを使用して数値を抽出できます。

    /// <summary>
    /// Example for how to extract the number from an xml string.
    /// </summary>
    /// <param name="xml"></param>
    /// <returns></returns>
    private string ExtractNumber(string xml)
    {
        // Extracted number.
        string number = string.Empty;

        // Input text
        xml = @"<string xmlns=""http://schemas.microsoft.com/2003/10/Serialization/"">2</string>";

        // The regular expression for the match.
        // You can use the parentesis to isolate the desired number into a group match. "(\d+?)"
        var pattern = @"<string.*?>(\d+?)</string>";

        // Match the desired part of the xml.
        var match = Regex.Match(xml, pattern);

        // Verify if the match has sucess.
        if (match.Success)
        {
            // Finally, use the group value to isolate the number.
            number = match.Groups[1].Value;
        }

        return number;
    }

これは、私がこの問題を解決するために使用した方法です。

于 2012-12-13T14:16:33.727 に答える