C#正则匹配问题:从含超链接字符串中匹配指定子串
解决C#正则匹配包含指定子串的问题
问题原因分析
你之前的正则匹配失败有两个核心问题:
^和$限定了必须完全匹配整个字符串,但目标子串只是输入字符串的一部分,并非全部内容。[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
相关产品推荐
相关产品推荐

