Ajit Goel
Ajit Goel

Reputation: 4388

Match string followed by another string

I have a regular expression newbie question. I am trying to do a case insensitive search in a string. I need to search cgif followed by any text and ending in .txt but the code below does not work. What am I missing?

using System;   
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var rx = new Regex("(cgif)+(.txt)+^", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        bool x1=rx.IsMatch("abc\\cgif123.txt");
        Console.WriteLine($"{x1}");<=should return true
        
        bool x2=rx.IsMatch("abc\\cgif.txt");
        Console.WriteLine($"{x2}");<=should return true
        
        bool x3=rx.IsMatch("abc\\cgif.txtabc");
        Console.WriteLine($"{x3}");<=should return false
    }
}

Upvotes: 0

Views: 59

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You should use

var rx = new Regex(@"cgif.*\.txt$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

NOTES:

  • RegexOptions.Singleline - will make . match newlines, LF, chars, too
  • cgif.*\.txt$ matches cgif, then any zero or more chars as many as possible, and then .txt at the end of string.

Here is a demo showing how this regex works. Also, see the online C# demo yielding True, True, False as expected.

Upvotes: 1

Related Questions