【问题标题】:Match string followed by another string匹配字符串后跟另一个字符串
【发布时间】:2021-08-17 01:49:59
【问题描述】:

我有一个正则表达式新手问题。 我正在尝试在字符串中进行不区分大小写的搜索。我需要搜索 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
    }
}

【问题讨论】:

  • 您学习了哪些正则表达式教程?将@"cgif.*\.txt$"| RegexOptions.Singleline 一起使用

标签: c# regex


【解决方案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 预期。

【讨论】:

  • @Joel \[.] 匹配 [,然后是任何字符,然后是 ]。要匹配一个点,需要\.
  • 您可能还想在 RegexOptions 中添加不区分大小写以使其完整
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多