我有一个正则表达式新手问题。
我正在尝试在字符串中进行不区分大小写的搜索。我需要搜索 cgif
后跟任何文本并以 .txt
结尾,但下面的代码不起作用。我错过了什么?
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
}
}
答案 0 :(得分:1)
你应该使用
var rx = new Regex(@"cgif.*\.txt$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
注意:
RegexOptions.Singleline
- 也会让 .
匹配换行符、LF、字符cgif.*\.txt$
匹配 cgif
,然后是尽可能多的零个或多个字符,然后是字符串末尾的 .txt
。这是一个 demo showing how this regex works。此外,请参阅 online C# demo 按预期产生 True, True, False
。