Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating pattern using regex in C#

Tags:

c#

regex

I have a string of words:

word dark king glow we end hello bye low wing

I need to find words where last letter of first word matches first letter of following word (example: worD Dark).

I wrote a regex expression:

\b\w*(\w)\W\1\w*\b

Currently it successfully finds 2 words in a row (Regex.Matches[0].Value = "word dark" ; Regex.Matches[1].Value = "king glow" etc.)

I need a regex expression which would read it as a pattern (Regex.Matches[0].Value = "word dark king glow we end" ; Regex.Matches[1].Value = "low wing").

How should I approach this?

like image 700
Gytis Dokšas Avatar asked Aug 22 '26 07:08

Gytis Dokšas


1 Answers

For the record here a very expressive non regex version. I does't require picture ;)

static IEnumerable<(string W1, string W2)> GetPairs1(string input)
{
    var words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);

    if (!words.Any()) yield break;

    for( int i = 1; i < words.Length; i++) 
        if(words[i][0] == words[i-1][words[i-1].Length-1]) 
            yield return (words[i-1], words[i]);
}

Test

public static async Task Main()
{
    var input = "word dark king glow we end hello bye low wing";

    foreach (var p in GetPairs1(input)) 
        Console.WriteLine($"{p.W1} {p.W2}");
}

Output

word dark
dark king
king glow
glow we
we end
low wing
like image 57
tymtam Avatar answered Aug 24 '26 19:08

tymtam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!