views:

169

answers:

5

my pattern is the following:

{(code)}
where code is a number (up to 6 digits), or 2 letter followed by a number.
For example:

{(45367)}
{(265367)}
{(EF127012)}

I want to find all occurrences in a long string, I can't just use pure regex , because I need to preform some action when i find a match (like logging the position and the type of the match).

+1  A: 
\{\(([A-Z]{2})?\d{1,6}\)\}
\{           # a literal { character
\(           # a literal ( character
(            # group 1
  [A-Z]{2}   #   letters A-Z, exactly two times
)?           # end group 1, make optional
\d{1,6}      # digits 0-9, at least one, up to six
\)           # a literal ) character
\}           # a literal } character
Tomalak
And what should I do with this regular expression? How do I use it in order to get position of every match?
ilann
There are literally *thousands* of examples of how to use regex in C#, on this site and everywhere else. It can't be that hard to find them.
Tomalak
+1  A: 

Use a MatchEvaluator with your regular expression to get the position and type of match.

http://en.csharp-online.net/CSharp_Regular_Expression_Recipes%E2%80%94Augmenting_the_Basic_String_Replacement_Function

bbudge
The only `Regex` methods that take a `MatchEvaluator` argument are the various `Replace` overloads, so this suggestion is only really applicable if the OP ultimately wants to perform some sort of replacement.
LukeH
+3  A: 

What you're referring to doing can still be done with regular expressions. Try the following...

Regex regex = new Regex(@"\{\(([A-Z]{2}\d{1,6}|\d{1,6})\)\}");
String test = @"my pattern is the following:

{(code)}
where code is a number (up to 6 digits), or 2 letter followed by a number.
For example:

{(45367)}
{(265367)}
{(EF127012)}

I want to find all occurrences in a long string, I can't just use pure regex , because I need to preform some action when i find a match (like logging the position and the type of the match).";
var matches = regex.Matches(test);
foreach (Match match in matches)
{
    MessageBox.Show(String.Format("\"{0}\" found at position {1}.", match.Value, match.Index));
}

I hope that helps.

Lance May
A: 

uncompiled and untested code sample

public void LogMatches( string inputText )
{
    var @TomalaksPattern = @"\{\(([A-Z]{2})?\d{6}\)\}"; // trusting @Tomalak on this, didn't verify
    MatchCollection matches = Regex.Matches( inputText, @TomalaksPattern );
    foreach( Match m in matches )
    {
        if( Regex.Match( m.Value, @"\D" ).Success )
             Log( "Letter type match {0} at index {1}", m.Value, m.Index );
        else
            Log( "No letters match {0} at index {1}", m.Value, m.Index );
    }
}
BioBuckyBall
A: 
foreach (Match m in Regex.Matches(yourString, @"(?:[A-Za-z]{2})?\d{1,6}"))
{
    Console.WriteLine("Index=" + m.Index + ", Value=" + m.Value);
}
LukeH