RegEx - 我应该使用Capture还是Group?

时间:2010-11-04 10:50:18

标签: .net regex vb.net

说我有这个列表(带有未知的分隔符):

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

我知道我需要的正则表达式是:[A-ZÆØÅ] {3} - \ d {5}。但是如何使用.net Match类的Group或Capture?

这是我的第一次尝试:

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 个答案:

答案 0 :(得分: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);
        }
    }
}

答案 1 :(得分: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