簡體   English   中英

如何使用正則表達式解析子字符串?

[英]How I can parse substring with regular expression ?

我的示例非解析數據是

"8$154#3$021308831#7$NAME SURNAME#11$2166220160#10$5383237309#52$05408166#"

我想解析$和#字符串之間的數據。 我想看到這樣的結果;

8$# ->我的數據是154
3$# ->我的數據是021308831
7$# ->我的數據是NAME SURNAME
11$# ->我的數據是2166220160
10$# ->我的數據是5383237309
52$# ->我的數據是05408166

感謝您的回復。

(\d+\$)(.*?)#

在Rubular上看到它

您將在捕獲組1中找到第一部分(例如8$ ),並在組2中找到相應的數據。

方括號負責,結果被那些捕獲組分類。 \\d+將至少匹配一位數字。 .*? 直到下一個#為止,一切都是懶惰的比賽。

您可以根據#拆分為數組。

String[] entries = data.Split('#');

您將得到一個包含“ 8 $ 154”,“ 3 $ 021308831”等的數組。

現在,您只需要處理條目並在美元符號處分割每個條目:

String[] tmp = entries[0].Split('$');

所以你得到

tmp[0] = "8";
tmp[1] = "154";

建立一些檢查,您會很高興的。 我想這里不需要正則表達式。

如果您擁有“ 8 $ 15 $ 4#3 $ 021308831”,那么您將獲得tmp

tmp[0] = "8"; // your key!
tmp[1] = "15"; // data part
tmp[2] = "4"; // data part ($ is missing!)

因此,您必須將所有tmp置於索引1之上:

StringBuilder value = new StringBuilder();
for(int i = 1; i < tmp.Length; i++)
{
    if(i > 1) value.Append("$");
    value.Append(tmp[i]);
}
class Program
{
    static void Main(string[] args)
    {
        string text = "8$154#3$021308831#7$NAME SURNAME#11$2166220160#10$5383237309#52$05408166#";
        string[] values = text.Split('$', '#');
        for (var i = 0; i < values.Length - 1; i = i + 2)
        {
            Console.WriteLine("Between " + values[i] + "$ and # -> My data is " + values[i+1]);
        }
        Console.ReadLine();
    }
}

好吧,以STEMA的表情為准

using System.Text.RegularExpressions;

string nonParsed = "8$...";

MatchCollection matches = Regex.Matches(nonparsed, @"(\d+\$)(.*?)#");

StringBuilder result = new StringBuilder();

for(int i = 0; i < matches.Count; i++)
{
    Match match = matches[i];

    result.AppendFormat("Between {0} and #-> My data is {1}")
        match.Groups[1].Value,
        match.Groups[2].Value);

    if (i < matches.Count - 1)
    {
        result.AppendLine(",");
    }
    else
    {
        result.Append(".");
    }
}

return result.ToString();

多虧了stema ,這才可以處理$在值內重復的現象。

如果要使用正則表達式,則應這樣做。

\$([\w\d\s]+)\#

這將與betweel $和#匹配:

\$(.*?)#

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM