我正在用C#开发一个windows应用程序。在创建Regex模式时,我一直在寻找问题的解决方案。我想创建一个匹配以下字符串之一的正则表达式模式:
XD=(111111) XT=( 588.466)m3 YT=( .246)m3 G=( 3.6)V N=(X0000000000) M=(Y0000000000) O=(Z0000000000) Date=(06.01.01)Time=(00:54:55) Q=( .00)m3/hr
XD=(111 ) XT=( 588.466)m3 YT=( .009)m3 G=( 3.6)V N=(X0000000000) M=(Y0000000000) O=(Z0000000000) Date=(06.01.01)Time=(00:54:55) Q=( .00)m3/hr具体的要求是,我需要上述给定字符串中的所有值,该字符串是键/值对的集合。此外,我想知道解决上述问题的two...Regex模式匹配或子字符串之外的正确方法(在效率和性能方面)。
提前感谢大家,如果需要更多细节,请让我知道。
发布于 2012-03-05 17:09:35
我不知道C#,所以可能有一种更好的方法来构建键/值数组。我构造了一个正则表达式,并将其传递给RegexBuddy,它生成了以下代码片段:
StringCollection keyList = new StringCollection();
StringCollection valueList = new StringCollection();
StringCollection unitList = new StringCollection();
try {
Regex regexObj = new Regex(
@"(?<key>\b\w+) # Match an alphanumeric identifier
\s*=\s* # Match a = (optionally surrounded by whitespace)
\( # Match a (
\s* # Match optional whitespace
(?<value>[^()]+) # Match the value string (anything except parens)
\) # Match a )
(?<unit>[^\s=]+ # Match an optional unit (anything except = or space)
\b # which must end at a word boundary
(?!\s*=) # and not be an identifier (i. e. followed by =)
)? # and is optional, as mentioned.",
RegexOptions.IgnorePatternWhitespace);
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
keyList.Add(matchResult.Groups["key"].Value);
valueList.Add(matchResult.Groups["value"].Value);
unitList.Add(matchResult.Groups["unit"].Value);
matchResult = matchResult.NextMatch();
} 发布于 2012-03-05 17:10:06
Regex re=new Regex(@"(\w+)\=\(([\d\s\.]+)\)");
MatchCollection m=re.Matches(s);m[0].Groups将拥有{ XD=(111111), XD, 111111 }m[1].Groups将拥有{ XT=( 588.466), XT, 588.466 }发布于 2012-03-05 17:12:21
String[] rows = { "XD=(111111) XT=( 588.466)m3 YT=( .246)m3 G=( 3.6)V N=(X0000000000) M=(Y0000000000) O=(Z0000000000) Date=(06.01.01)Time=(00:54:55) Q=( .00)m3/hr",
"XD=(111 ) XT=( 588.466)m3 YT=( .009)m3 G=( 3.6)V N=(X0000000000) M=(Y0000000000) O=(Z0000000000) Date=(06.01.01)Time=(00:54:55) Q=( .00)m3/hr" };
foreach (String s in rows) {
MatchCollection Pair = Regex.Matches(s, @"
(\S+) # Match all non-whitespace before the = and store it in group 1
= # Match the =
(\([^)]+\S+) # Match the part in brackets and following non-whitespace after the = and store it in group 2
", RegexOptions.IgnorePatternWhitespace);
foreach (Match item in Pair) {
Console.WriteLine(item.Groups[1] + " => " + item.Groups[2]);
}
Console.WriteLine();
}
Console.ReadLine();如果您还想提取单元,那么使用这个正则表达式
@"(\S+)=(\([^)]+(\S+))我在它周围添加了一组括号,然后您将在item.Groups[3]中找到该单元
https://stackoverflow.com/questions/9563858
复制相似问题