[英]Regex matching mixed string segments containing operator, string designator, and curly-brace group
我正在寻找一个 C# 正则表达式解决方案来匹配/捕获一些小而复杂的数据块。 我的数据库中有数千个非结构化数据块(来自第三方数据存储),看起来类似于:
not BATTCOMPAR{275} and FORKCARRIA{ForkSpreader} and SIDESHIFT{WithSSPassAttachCenterLine} and TILTANGLE{4up_2down} and not AUTOMATSS{true} and not FORKLASGUI{true} and not FORKCAMSYS{true} and OKED{true}
我希望能够将其拆分为离散的部分(正则表达式匹配/捕获),如下所示:
not BATTCOMPAR{275}
and FORKCARRIA{ForkSpreader}
and SIDESHIFT{WithSSPassAttachCenterLine}
and TILTANGLE{4up_2down}
and not AUTOMATSS{true}
and not FORKLASGUI{true}
and not FORKCAMSYS{true}
and OKED{true}
数据将始终符合以下规则:
{275}
not
or and
or and not
or nothing 开头的字符串的末尾。 "nothing" 与 and 相同and
并且只会在它是字符串中的第一个块时出现。 例如,如果 my and OKED{true}
出现在字符串的开头,则and
将被省略,并且OKED{true}
将没有任何前缀(空字符串)。 但它与and 相同。and
or not
or and not
or nothing)之后,总会有一个字符串指示符,它在花括号分组之前结束。 示例: BATTCOMPAR
and not
)、字符串指示符(例如BATTCOMPAR
)和花括号分组(例如{ForkSpreader}
)。我尝试了几种不同的正则表达式结构:
匹配花括号分组:
Regex regex = new Regex(@"{(.*?)}");
return regex.Matches(str);
以上几乎可以工作,但只得到花括号分组,而不是随之而来的运算符和字符串指示符。
根据字符串前缀捕获块,尝试匹配运算符字符串:
var capturedWords = new List<string>();
string regex = $@"(?<!\w){prefix}\w+";
foreach ( Match match in Regex.Matches(haystack, regex) ) {
capturedWords.Add(match.Value);
}
return capturedWords;
以上部分有效,但仅获得运算符,而不是我需要的整个块:(运算符 + 字符串指示符 + 花括号分组)
提前感谢您的帮助。
最简单的解决方案似乎是使用这个正则表达式和split
:
new Regex(@"[ ](?=and)");
它只是拆分后跟and
的空格:
Regex regex = new Regex(@"[ ](?=and)");
return regex.Split(str);
你可以在这里看到结果: NetRegexBuilder
这对我有用: /([and\w|or\w|not\w]+?.*?\{.*?\})/m
在Regex Tester
上。
在DotNet Fiddle
上,这对我有用:
string test = "not BATTCOMPAR{275} and FORKCARRIA{ForkSpreader} and SIDESHIFT{WithSSPassAttachCenterLine} and TILTANGLE{4up_2down} and not AUTOMATSS{true} and not FORKLASGUI{true} and not FORKCAMSYS{true} and OKED{true}";
Regex r = new Regex("([and\\w|or\\w|not\\w]+?.*?\\{.*?\\})", RegexOptions.Multiline);
MatchCollection matches = r.Matches(test);
foreach(Match m in matches)
{
Console.WriteLine(m.Value);
}
印刷:
//not BATTCOMPAR{275}
//and FORKCARRIA{ForkSpreader}
//and SIDESHIFT{WithSSPassAttachCenterLine}
//and TILTANGLE{4up_2down}
//and not AUTOMATSS{true}
//and not FORKLASGUI{true}
//and not FORKCAMSYS{true}
//and OKED{true}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.