登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  文章 >  软件教程

C# 正则表达式(4):分支与回溯引用

时间:2026-08-21 10:04:31 340浏览 收藏

一、分支 |:在多个候选中选一个

1. 最基本的 |

Regex.IsMatch("my dog", @"cat|dog"); // True

2. 分支几乎总要配合分组

(?:...) 是非捕获分组,用于“只分组,不提取”。

C# 正则表达式(4):分支与回溯引用

Console.WriteLine( Regex.IsMatch("https://www.baidu.com", @"(?:http|https)://")); // True
  • 想匹配 jpg/png/gif 结尾的文件名:
Console.WriteLine( Regex.IsMatch("a.png", @"^.+.(?:jpg|png|gif)$")); // True

二、分支的优先级与“从左到右”匹配

正则引擎通常会“先尝试左边分支”,成功就不再看右边。

因此把短分支放在长分支前面,会导致长分支永远匹配不到。

Console.WriteLine( Regex.IsMatch("ab", @"^(?:ab|a)$")); // True

三、回溯引用:让后面必须“重复前面匹配到的内容”

回溯引用依赖捕获组:(...)

  • 数字回溯引用:12…(引用第 1、2…个捕获组)
  • 命名回溯引用:k(引用名为 name 的捕获组)

1. 匹配成对引号(单引号或双引号),并确保左右一致

示例:

匹配 "hello" 或者 'hello' ,但不允许像 "hello' 这样左右引号不一致的情况出现。

正则:

^(["'])(?.*)1$

解析::

  • (["']) 捕获一个引号字符(单或双),这是组 1
  • (?.*) 捕获内容
  • 1 要求结尾引号必须和开头引号完全相同
string[] inputs = { ""hello"", "'hello'", ""hello'", "'hello"" };
var pattern = @"^([""'])(?.*)1$";

foreach (var s in inputs)
{
    var m = Regex.Match(s, pattern);
    Console.WriteLine($"{s} -> {m.Success}");
}

2. 匹配重复单词(如 “hello hello”)

需求:匹配两个相同单词,中间用空白分隔。

b(w+)s+1b

示例:

var text = "This is is a test, hello hello!";
var pattern = @"b(w+)s+1b";

foreach (Match m in Regex.Matches(text, pattern))
{
    Console.WriteLine(m.Value); // "is is", "hello hello"
}

3. 命名回溯引用:k

把引号例子改成命名更清晰:

var text = "This is is a test, hello hello!";
var pattern = @"b(?w+)s+kb";

foreach (Match m in Regex.Matches(text, pattern))
{
    Console.WriteLine(m.Value); // "is is", "hello hello"
}

结语

觉得有用就点个赞吧!关注我,更多实用C#技术干货等你来发现!别忘了收藏本文哦

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>