简体   繁体   中英

regex not giving all the possible matches

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?

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM