2

我是一个正则表达式的菜鸟。我有一堆要解析的用户代理字符串。

Windows Phone 搜索 (Windows Phone OS 7.10;Acer;Allegro;7.10;8860)
Windows Phone 搜索 (Windows Phone OS 7.10;HTC;7 Mozart T8698;7.10;7713)
Windows Phone 搜索 (Windows Phone OS 7.10;HTC;Radar C110e; 7.10;7720)

我如何使用正则表达式来提取:

A) Windows Phone 操作系统 7.10 宏碁 Allegro

B) Windows Phone 操作系统 7.10 HTC 7 莫扎特

C) Windows Phone OS 7.10 HTC 雷达

我尝试通过Split以下方式使用,但无济于事:

private static string parse(string input) 
{ 
    input = input.Remove(0, input.IndexOf('(') + 1).Replace(')', ' ').Trim(); 
    string[] temp = input.Split(';'); 
    if (temp[2].Contains('T'))
    { 
        temp[2] = temp[2].Substring(0, temp[2].IndexOf('T')).Trim(); 
    } 
    StringBuilder sb = new StringBuilder(); 
    sb.Append(temp[0] + " "); 
    sb.Append(temp[1] + " "); 
    sb.Append(temp[2]); 
    return sb.ToString(); 
}
4

2 回答 2

1

此正则表达式将捕获它:

(?<=\().*?;.*?;.*?(?=;)

作为代码,它将是:

string s = Regex.Match(input, @"(?<=\().*?;.*?;.*?(?=;)").Value

作为正则表达式的细分:

  • (?<=\()= 断言前一个字符的“后看”是文字左括号(
  • .*?;= 一个(非贪婪 - 不会跳过;)匹配到下一个的所有内容;
  • (?=;)= 断言下一个字符的“前瞻”是文字分号;
于 2013-07-12T15:25:45.993 回答
1

我使用正则表达式是因为它专门用于解析任何类型的文本。一旦理解了正则表达式模式的基础知识,它在任何文本情况下都会变得非常有用。

在这种模式中,我的目标是将每个项目分成命名的版本、电话、类型、主要和次要的捕获组。一旦通过正则表达式处理完成,我可以使用 Linq 提取数据,如图所示。

string @pattern = @"
(?:OS\s)                     # Match but don't capture (MDC) OS, used an an anchor
(?<Version>\d\.\d+)          # Version of OS
(?:;)                        # MDC ;
(?<Phone>[^;]+)              # Get phone name up to ;
(?:;)                        # MDC ;
(?<Type>[^;]+)               # Get phone type up to ;
(?:;)                        # MDC ;
(?<Major>\d\.\d+)            # Major version
(?:;)
(?<Minor>\d+)                # Minor Version
";

string data =
@"Windows Phone Search (Windows Phone OS 7.10;Acer;Allegro;7.10;8860)
Windows Phone Search (Windows Phone OS 7.10;HTC;7 Mozart T8698;7.10;7713)
Windows Phone Search (Windows Phone OS 7.10;HTC;Radar C110e;7.10;7720)";

 // Ignore pattern white space allows us to comment the pattern, it is not a regex processing command
var phones = Regex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace)
                  .OfType<Match>()
                  .Select (mt => new
                  {
                    Name = mt.Groups["Phone"].Value.ToString(),
                    Type = mt.Groups["Type"].Value.ToString(),
                    Version = string.Format( "{0}.{1}", mt.Groups["Major"].Value.ToString(),
                                                        mt.Groups["Minor"].Value.ToString())
                  }
                  );

Console.WriteLine ("Phones Supported are:");

phones.Select(ph => string.Format("{0} of type {1} version ({2})", ph.Name, ph.Type, ph.Version))
      .ToList()
      .ForEach(Console.WriteLine);

/* Output
Phones Supported are:
Acer of type Allegro version (7.10.8860)
HTC of type 7 Mozart T8698 version (7.10.7713)
HTC of type Radar C110e version (7.10.7720)
*/
于 2013-07-12T17:29:43.483 回答