2009-12-17 50 views
0

我想使用正则表达式来标识字符串中的某些单词。VS2008 C#:正则表达式和标识某些单词

例如:

"bla bla bla | First Name = John Doe | City = Denver | bla bla bla | State = CA | bla bla bla" 

在上述字符串,即|我想分析出名字,城市和州的内容,并将它们存储在散列表中的某些地方。

我该如何去做呢?我认为最好的方法是使用正则表达式。

+0

但后来我将如何能够捕捉键值对,例如City,State,FirstName等。 – 2009-12-17 17:29:05

回答

0

我会使用string.Split('|')和string.IndexOf(“=”)来解析元素。它肯定比正则表达式更直接。

0

如果您的数据一致(即始终使用|和=作为分隔符),则可以使用字符串split方法在数组中获取结果。

4

只是使用拆分不会更容易吗?

例子:

var test = "bla bla bla | First Name = John Doe | City = Denver | bla bla bla | State = CA | bla bla bla"; 
var sections = test.Split('|'); 
var firstName = sections[1].Split('=')[1].Trim(); 
var city= sections[2].Split('=')[1].Trim(); 
var state= sections[4].Split('=')[1].Trim(); 
1

使用Split()功能:

public class SplitTest { 
    public static void Main() { 

     string words = "This is a list of words, with: a bit of punctuation" + 
         "\tand a tab character."; 

     string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' }); 

     foreach (string s in split) { 

      if (s.Trim() != "") 
       Console.WriteLine(s); 
     } 
    } 
} 
// The example displays the following output to the console: 
//  This 
//  is 
//  a 
//  list 
//  of 
//  words 
//  with 
//  a 
//  bit 
//  of 
//  punctuation 
//  and 
//  a 
//  tab 
//  character 
1

使用命名组是非常简单的...

// named groups are very cool for this... 
    public static Regex regex = new Regex("\\|(?:\\s*)(?<key>(\\w+)(\\s*))=(?<value>[^|]+)", RegexOptions.CultureInvariant | RegexOptions.Compiled); 

    public static Dictionary<string, string> Extract(string line) 
    { 
     Dictionary<string, string> results = new Dictionary<string, string>();   
     foreach (Match match in regex.Matches(line)) 
     { 
      var groupKey = match.Groups["key"]; 
      var groupValue = match.Groups["value"]; 
      if (groupKey.Success && groupValue.Success) 
      { 
       // add the group value trimmed as we might have extra blank spaces 
       results[groupKey.Value.Trim()] = groupValue.Value.Trim(); 
      } 
     } 
     return results; 
    }