You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#正则匹配问题:从含超链接字符串中匹配指定子串

解决C#正则匹配包含指定子串的问题

问题原因分析

你之前的正则匹配失败有两个核心问题:

  1. ^ 和 $ 限定了必须完全匹配整个字符串,但目标子串只是输入字符串的一部分,并非全部内容。
  2. [a-zA-Z0-9]* 只能匹配字母数字,无法覆盖超链接里的特殊字符(比如://、.、/等),导致子串前后的超链接内容被正则排除,无法匹配。

正确的正则表达式

根据你的需求,只需检查字符串中存在指定子串即可,推荐两种写法:

写法1:直接匹配子串(最简单)

适用于仅需判断子串是否存在的场景:

new Regex(@"your policy may provide coverage with the Rideshare Coverage")

写法2:匹配包含子串的任意内容(支持跨行)

如果字符串包含换行,添加Singleline选项让.匹配换行符:

new Regex(@".*your policy may provide coverage with the Rideshare Coverage.*", RegexOptions.Singleline)

示例代码

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Sample text with link https://example.com 12345 your policy may provide coverage with the Rideshare Coverage more content here";
        
        // 基础匹配(不跨行)
        bool basicMatch = Regex.IsMatch(input, @"your policy may provide coverage with the Rideshare Coverage");
        Console.WriteLine($"基础匹配结果:{basicMatch}");
        
        // 跨行匹配
        string multilineInput = "Text with\nline break and https://test.com\n your policy may provide coverage with the Rideshare Coverage\n end text";
        bool multilineMatch = Regex.IsMatch(multilineInput, @".*your policy may provide coverage with the Rideshare Coverage.*", RegexOptions.Singleline);
        Console.WriteLine($"跨行匹配结果:{multilineMatch}");
    }
}

内容的提问来源于stack exchange,提问作者VishalTest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:40:07