Question

I need to get all the possible matches for a given regular expression and word in c#. But the Regex.Matches() function is not giving it. For eg.

Regex.Matches("datamatics","[^aeiou]a[^aeiou]")

returns only two matches which are

dat
mat

it is not giving "tam" as a match. Can somebody explain to me why it is not giving "tam" as a match and how can I get all the three?

Was it helpful?

Solution 2

You can't get overlapping matches in Regex. You have several ways to work around it, though. You can either use Regex.Match, and specify a starting index (use a loop to go through your whole string), or you can use lookbehinds or lookaheads, like so:

  (?=[^aeiou]a)[^aeiou]

This works because lookbehinds and lookaheads do not consume the characters. It returns a Match which contains the index of the match. You'd need to use that instead of captures, since only one character is captured.

OTHER TIPS

Use this regex

(?<=([^aeiou]))a(?=([^aeiou]))

.net supports group capture in lookarounds..cheers

Your code would be

var lst= Regex.Matches(input,regex)
              .Cast<Match>()
              .Select(x=>x.Groups[1].Value+"a"+x.Groups[2].Value)
              .ToList();

Now you can iterate over lst

foreach(String s in lst)
{
     s;//required strings
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top