我有以下格式的字符串。
"ABC 12.23-22-22-11|-ABC 33.20-ABC 44.00-ABC 11.00|ABC 12.23-22-22-11|-ABC 33.20-ABC 44.00-ABC11.00|ABC 12.23-22-22-11|-ABC 33.20-ABC 44.00-ABC 11.00";
我想做的是找到下一个以管道开头但后面没有-的组
因此,上面的字符串将指向3个部分,例如
ABC 12.23-22-22-11|-ABC 33.20-ABC 44.00-ABC 11.00
ABC 12.23-22-22-11|-ABC 33.20-ABC 44.00-ABC 11.00
ABC 12.23-22-22-11|-ABC 33.20-ABC 44.00-ABC 11.00
我玩了下面的代码,但它似乎没有做任何事情,它没有给我下一个块的位置,在此块中,管道字符不带破折号(-)
String pattern = @"^+|[A-Z][A-Z][A-Z]$";
在上面我的逻辑是
1:Start from the beginning
2:Find a pipe character which is not followed by a dash char
3:Return its position
4:Which I will eventually use to substring the blocks
5:And do this till the end of the string
请不要客气,因为我不知道正则表达式如何工作,我只是在尝试使用它。谢谢,语言是C#
最佳答案
您可以将Regex.Split
method与\|(?!-)
模式一起使用。
注意,您需要转义|
字符,因为它是正则表达式中用于交替的元字符。 (?!-)
是否定的前瞻,当在|
字符后出现破折号时,它将停止匹配。
var pattern = @"\|(?!-)";
var results = Regex.Split(input, pattern);
foreach (var match in results) {
Console.WriteLine(match);
}