开发者

RegEx - Should I use Capture or Group?

Say I have this list (with unknown delimiters):

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

I know the regex to mach what I need is: [A-ZÆØÅ]{3}-\d{5}. But how do I use the Group or Capture of the .net Match class?

This is my first attempt:

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
开发者_高级运维

I want to return a list of my matches. Any ideas?

Larsi


I think this does what you want (C#, but the VB will be similar):

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);
        }
    }
}

Note the use of Regex.Matches instead of Regex.Match, to find all the matches.

And here's a value which puts them into a List<string> using LINQ:

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);
        }
    }
}


How about this?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜