Wednesday, October 2, 2013

Non-greedy regular expression not working

I figured out how to handle the non greedy cases



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static string[] inputs = {
"[text1][text2][text3]",
"[text1]",
"[text1] Other Text [text2][text3]",
"[text1][text2]"
};
static void Main(string[] args)
{
string pattern = @"(\[(?'word'\w+)\]){3}(?'bad'.*)$" +
@"|(\[(?'word'\w+)\]){1}(?'bad'.*)$";
Regex expr = new Regex(pattern);
foreach (string input in inputs)
{
int wordCountcount = 1;
Match match = expr.Match(input);
if (match.Groups["bad"].Value.Trim().Length > 0)
{
Console.WriteLine("Bad input : {0}", match.Groups["bad"].Value);
}
else
{
foreach (Capture capture in match.Groups["word"].Captures)
{
Console.Write("Word {0} : {1}; ", wordCountcount, capture.Value);
wordCountcount++;
}
Console.WriteLine();
}
}
}
}
}





jdweng


No comments:

Post a Comment