1

我有这些格式的数据

"NEW ITEM:1_BELT:3_JEANS:1_BELT:1_SUIT 3 PCS:1_SHOES:1"

格式是Item1:Item1Qty_Item2:Item2Qty.........ItemN:ItemNQty

我需要将物品及其相应的数量分开并形成数组。我做了这样的项目部分..

var allItemsAry = Regex.Replace(myString, "[\\:]+\\d", "").Split('_');

现在allItemsAry是这样的[NEW ITEM, BELT, JEANS, BELT, SUIT 3 PCS, SHOES]

但是我无法弄清楚如何获得数量,无论我尝试什么表达3SUIT 3 PCS伴随着那个,就像这些

var allQtyAry = Regex.Replace(dataForPackageConsume, "[^(\\:+\\d)]", "").split(':') 

这出现为:1:3:1:13:1:1(替换时)。所以我不能分开:来让它成为数组,正如可以看到的第四项是13,而它应该是1,那3是来自SUIT 3 PCS。我还尝试了其他一些变化,但总是会3出现SUIT 3 PCS。我如何才能获得衣服的数量(可能附有:这样我可以将它们分开并形成阵列?

更新:如果我在想要完全以分号开头的数字: 之前没有说清楚。

所以,我想要的是:1:3:1:1:1:1

4

5 回答 5

3

与其删除除数字之外的所有内容,不如只匹配数字

例如:

Regex regex = new Regex(@":\d+");
string result = string.Empty;
foreach (Match match in regex.Matches(input))
    result += match.Value;
于 2013-06-13T10:45:21.717 回答
3

[^\d:]+|:(?!\d)|(?<!:)\d+

[^\d:]+将匹配所有非数字非:s。

:(?!\d)将匹配所有:不跟数字的 s(负前瞻)。

(?<!:)\d+将匹配所有前面没有:(负向后看)的数字。


资源

NEW ITEM:1_BELT:3_JEANS:1_BELT:1_SUIT 3 PCS:1_SHOES:1

正则表达式

[^\d:]+|:(?!\d)|(?<!:)\d+

结果匹配

NEW ITEM
_BELT
_JEANS
_BELT
_SUIT 
3
 PCS
_SHOES
于 2013-06-13T10:56:48.127 回答
2

你想要它只有数字:1:3:1:1:3:1:1吗?

string s = "NEW ITEM:1_BELT:3_JEANS:1_BELT:1_SUIT 3 PCS:1_SHOES:1";
var output = Regex.Replace(s, @"[^0-9]+", "");
StringBuilder sb = new StringBuilder();
foreach (var i in output)
{
    sb.Append(":" + i);
}
Console.WriteLine(sb); // :1:3:1:1:3:1:1

这是一个DEMO.

好的,如果之后每个字符都是数字:那么您可以像这样使用它;

string s = "NEW ITEM:1_BELT:3_JEANS:1_BELT:1_SUIT 3 PCS:1_SHOES:1";
var array = s.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (var item in array)
{
    if (Char.IsDigit(item[0]))
    {
        sb.Append(":" + item[0]);
    }
}

Console.WriteLine(sb); //:1:3:1:1:1:1

演示

于 2013-06-13T10:27:09.973 回答
1

This will work with one replace:

var allQtyAry = Regex.Replace(dataForPackageConsume, @"[^_:]+:", "").split('_')

Explanation:

[^_:] means match anything that's not a _ or a :

[^_:]+: means match any sequence of at least one character not matching either _ or :, but ending with a :

Since regular expressions are greedy by default (ie they grab as much as possible), matching will start at the beginning of the string or after each _:

NEW ITEM: 1_BELT: 3_JEANS: 1_BELT: 1_SUIT 3 PCS: 1_SHOES: 1

Removing the matched parts (the italic bold bits above) results in:

1_3_1_1_1_1

Splitting by _ results in:

[1, 3, 1, 1, 1, 1]

于 2013-06-13T10:53:45.567 回答
0

试试这个正则表达式[^:\d+?].*?(?=:),它应该可以解决问题

string[] list = Regex.Replace(test, @"[^:\d+?].*?(?=:)", string.Empty).Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

正则表达式匹配并用空字符串替换冒号之前的所有内容: (exclusive) .*?(?=:)。它还从匹配中排除:#[^:\d+?] ,因此您:1:3:1:1:1:1在拆分之前最终得到

于 2013-06-15T05:23:02.107 回答