2010-11-04 87 views
0

说我有这个名单(未知分隔符):RegEx - 我应该使用Capture还是Group?

ABC-12345, DEF-34567; WER-12312 \n ERT-23423 

我知道正则表达式马赫我需要的是:A-ZÆØÅ] {3} - \ d {5}。但是,如何使用.net匹配类的组或捕获?

这是我第一次尝试:

Public Function ParseSites(ByVal txt As String) As List(Of String) 
    Const SiteIdRegEx = "([A-ZÆØÅ]{3}-\d{5})" 
    Dim list As New List(Of String) 
    Dim result As Match = Regex.Match(txt, SiteIdRegEx) 
    For Each item As Capture In result.Captures 
     If (Not String.IsNullOrEmpty(item.Value)) Then 
      list.Add(item.Value) 
     End If 
    Next 
    Return list 
End Function 

我想要回我的比赛名单。有任何想法吗?

Larsi

回答

2

我想这你想要做什么(C#,但VB将是相似的):

using System; 
using System.Text.RegularExpressions; 

public class Test 
{ 
    static void Main() 
    { 
     Regex regex = new Regex(@"[A-ZÆØÅ]{3}-\d{5}"); 
     string text = "ABC-12345, DEF-34567; WER-12312 \n ERT-23423"; 

     foreach (Match match in regex.Matches(text)) 
     { 
      Console.WriteLine("Found {0}", match.Value); 
     } 
    } 
} 

注意使用Regex.Matches代替Regex.Match,找到所有比赛。

下面是使用LINQ这使他们成为List<string>值:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text.RegularExpressions; 

public class Test 
{ 
    static void Main() 
    { 
     Regex regex = new Regex(@"[A-ZÆØÅ]{3}-\d{5}"); 
     string text = "ABC-12345, DEF-34567; WER-12312 \n ERT-23423"; 
     List<string> values = regex.Matches(text) 
            .Cast<Match>() 
            .Select(x => x.Value) 
            .ToList(); 

     foreach (string value in values) 
     { 
      Console.WriteLine("Found {0}", value); 
     } 
    } 
} 
+0

Ahhh ..有一个MatchES功能。谢谢 – Larsi 2010-11-04 11:09:49

0

这个怎么样?

Dim AllMatchResults As MatchCollection 
Dim RegexObj As New Regex("[A-ZÆØÅ]{3}-\d{5}") 
AllMatchResults = RegexObj.Matches(SubjectString) 
If AllMatchResults.Count > 0 Then 
    ' Access individual matches using AllMatchResults.Item[] 
Else 
    ' Match attempt failed 
End If 
+0

感谢您提供sln。 – Larsi 2010-11-04 11:11:00