简体   繁体   English

使用正则表达式拆分数据(正则表达式)

[英]Splitting data with Regex (Regular Expressions)

I would need some help with matching data in this example string: 在此示例字符串中,我将需要一些与数据匹配的帮助:

 req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}

Essentially, every parameter is separated by "," but it is also included within {} and I need some help with regex as I am not that good with it. 本质上,每个参数都用“,”分隔,但它也包含在{}中,我需要一些正则表达式的帮助,因为我不太喜欢它。

Desired Output: 所需输出:

req = "REQUESTER_NAME"
key = "abc"
act = "UPDATE"
sku[0] = "ABC123"
sku[1] = "DEF-123"
qty[0] = 10
qty[1] = 5

I would suggest you do the following 我建议您执行以下操作

  1. Use String Split with ',' character as the separator (eg output req:{REQUESTER_NAME}) 使用带有','字符的字符串拆分作为分隔符(例如,输出req:{REQUESTER_NAME})
  2. With each pair of data, do String Split with ';' 对于每对数据,使用“;”进行字符串分割 character as the separator (eg output "req", "{REQUESTER_NAME}") 字符作为分隔符(例如输出“ req”,“ {REQUESTER_NAME}”)
  3. Do a String Replace for characters '{' and '}' with "" (eg output REQUESTER_NAME) 用“”替换字符串“ {”和“}”(例如输出REQUESTER_NAME)
  4. Do a String Split again with ',' character as separator (eg output "ABC123", "DEF-123") 再次使用“,”字符作为分隔符进行字符串拆分(例如,输出“ ABC123”,“ DEF-123”)

That should parse it for you perfectly. 那应该为您完美解析。 You can store the results into your data structure as the results come in. (Eg. You can store the name at step 2 whereas the value for some might be available at Step 3 and for others at Step 4) 您可以在结果输入时将结果存储到数据结构中。(例如,您可以在步骤2中存储名称,而某些名称可能在步骤3中可用,而其他名称可能在步骤4中可用)

Hope That Helped 希望有帮助

Note: - If you don't know string split - http://www.dotnetperls.com/split-vbnet - If you don't know string replace - http://www.dotnetperls.com/replace-vbnet 注意:-如果您不知道字符串拆分-http: //www.dotnetperls.com/split-vbnet-如果您不知道字符串替换-http: //www.dotnetperls.com/replace-vbnet

The below sample may helps to solve your problem. 以下示例可能有助于解决您的问题。 But here lot of string manipulations are there. 但是这里有很多字符串操作。

        string input = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}";

        Console.WriteLine(input);

        string[] words = input.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string item in words)
        {
            if (item.Contains(':'))
            {
                string modifiedString = item.Replace(",", "," + item.Substring(0, item.IndexOf(':')) + ":");

                string[] wordsColl = modifiedString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string item1 in wordsColl)
                {
                    string finalString = item1.Replace("{", "");
                    finalString = finalString.Replace("}", "");
                    Console.WriteLine(finalString);
                }
            }
        }

First, use Regex.Matches to get the parameters inside { and } . 首先,使用Regex.Matches获取{}的参数。

string str = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}";
MatchCollection matches = Regex.Matches(str,@"\{.+?\}");
string[] arr = matches.Cast<Match>()
                    .Select(m => m.Groups[0].Value.Trim(new char[]{'{','}',' '}))
                    .ToArray();
foreach (string s in arr)
    Console.WriteLine(s);

output 输出

REQUESTER_NAME
abc
UPDATE
ABC123,DEF-123
10,5

then use Regex.Split to get the parameter names 然后使用Regex.Split来获取参数名称

string[] arr1 = Regex.Split(str,@"\{.+?\}")
                         .Select(x => x.Trim(new char[]{',',':',' '}))
                         .Where(x => !string.IsNullOrEmpty(x)) //need this to get rid of empty strings
                         .ToArray();
foreach (string s in arr1)
    Console.WriteLine(s);

output 输出

req
key
act
sku
qty

Now you can easily traverse through the parameters. 现在,您可以轻松遍历参数。 something like this 像这样的东西

for(int i=0; i<arr.Length; i++)
{
    if(arr1[i] == "req")
        //arr[i] contains req parameters
    else if(arr1[i] == "sku")
        //arr[i] contains sku parameters
        //use string.Split(',') to get all the sku paramters and process them
}

Kishore's answer is correct. Kishore的答案是正确的。 This extension method may help implement that suggestion: 此扩展方法可能有助于实现该建议:

<Extension()>
Function WideSplit(InputString As String, SplitToken As String) As String()
    Dim aryReturn As String()
    Dim intIndex As Integer = InputString.IndexOf(SplitToken)
    If intIndex = -1 Then
        aryReturn = {InputString}
    Else
        ReDim aryReturn(1)
        aryReturn(0) = InputString.Substring(0, intIndex)
        aryReturn(1) = InputString.Substring(intIndex + SplitToken.Length)
    End If
    Return aryReturn
End Function

If you import System.Runtime.CompilerServices, you can use it like this: 如果导入System.Runtime.CompilerServices,则可以像这样使用它:

Dim stringToParse As String = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}"
Dim strTemp As String
Dim aryTemp As String()
strTemp = stringToParse.WideSplit("req:{")(1)
aryTemp = strTemp.WideSplit("},key:{")
req = aryTemp(0)
aryTemp = aryTemp(1).WideSplit("},act:{")
key = aryTemp(0)
'etc...

You may be able do this more memory efficiently, though, as this method creates a number of temporary string allocations. 但是,由于此方法会创建许多临时的字符串分配,因此您可能可以更有效地执行此操作。

Kishore's solution is perfect, but here is another solution that works with regex: Kishore的解决方案是完美的,但是这里是另一种与正则表达式一起使用的解决方案:

Dim input As String = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}"
Dim Array = Regex.Split(input, ":{|}|,")

This does essentially the same, it uses regex to split on :{ , } and , . 这样做基本相同,它使用正则表达式分割:{}, The solution might be a bit shorter though. 解决方案可能会短一些。 The values will be put into the array like this: 这些值将像这样放入数组:

"req", "REQUESTER_NAME","", ... , "qty", "10", "5", ""

Notice after the parameter and its value(s) there will be an empty string in the array. 请注意,在参数及其值之后,数组中将有一个空字符串。 When looping over the array you can use this to let the program know when a new parameter starts. 当遍历数组时,可以使用它来让程序知道新参数何时开始。 Then you can create a new array/data structure to store its values. 然后,您可以创建一个新的数组/数据结构来存储其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM