// 正则表达式测试器 - getgreentool.com // C# WinForms 单文件,零第三方依赖。正则引擎用 .NET 内置 System.Text.RegularExpressions。 // CLI: --selftest 跑内置断言(兼容末尾多传临时目录参数)。 using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace RegexToolApp { // ---------- 纯逻辑层 ---------- public static class RegexOps { public sealed class MatchInfo { public int Index; // 0-based 字符位置 public int Length; // 字符长度 public string Value; // 匹配文本 public string[] Groups; // 捕获组(组1起),未参与为 null } public static RegexOptions BuildOptions(bool ignoreCase, bool multiline, bool singleline) { RegexOptions o = RegexOptions.None; if (ignoreCase) o |= RegexOptions.IgnoreCase; if (multiline) o |= RegexOptions.Multiline; if (singleline) o |= RegexOptions.Singleline; return o; } // 校验表达式本身,非法时返回人类可读错误;合法返回 null public static string Validate(string pattern) { if (string.IsNullOrEmpty(pattern)) return "表达式为空"; try { new Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); return null; } catch (ArgumentException ex) { return ShortErr(ex.Message ?? ""); } } // 超时保护:防灾难性回溯卡死界面 public const int TimeoutMs = 1000; public static List FindAll(string pattern, string input, RegexOptions options, out string error) { error = null; string v = Validate(pattern); if (v != null) { error = v; return null; } if (input == null) input = ""; try { var re = new Regex(pattern, options, TimeSpan.FromMilliseconds(TimeoutMs)); var list = new List(); foreach (Match m in re.Matches(input)) { var mi = new MatchInfo { Index = m.Index, Length = m.Length, Value = m.Value }; var gs = new string[m.Groups.Count - 1]; for (int i = 1; i < m.Groups.Count; i++) gs[i - 1] = m.Groups[i].Success ? m.Groups[i].Value : null; mi.Groups = gs; list.Add(mi); if (list.Count >= 500) break; // 上限防刷屏 } return list; } catch (RegexMatchTimeoutException) { error = "匹配超时(>" + TimeoutMs + "ms),表达式可能存在灾难性回溯"; return null; } catch (ArgumentException ex) { error = ShortErr(ex.Message); return null; } } public static string Replace(string pattern, string input, string replacement, RegexOptions options, out string error) { error = null; string v = Validate(pattern); if (v != null) { error = v; return null; } if (input == null) input = ""; if (replacement == null) replacement = ""; try { var re = new Regex(pattern, options, TimeSpan.FromMilliseconds(TimeoutMs)); return re.Replace(input, replacement); } catch (RegexMatchTimeoutException) { error = "替换超时,表达式可能存在灾难性回溯"; return null; } catch (ArgumentException ex) { error = ShortErr(ex.Message); return null; } } // 替换预览统计:替换了几处 public static int ReplaceCount(string pattern, string input, RegexOptions options, out string error) { error = null; string v = Validate(pattern); if (v != null) { error = v; return -1; } try { var re = new Regex(pattern, options, TimeSpan.FromMilliseconds(TimeoutMs)); int n = 0; re.Replace(input ?? "", m => { n++; return m.Value; }); return n; } catch (RegexMatchTimeoutException) { error = "统计超时,表达式可能存在灾难性回溯"; return -1; } catch (ArgumentException ex) { error = ShortErr(ex.Message); return -1; } } public static string ShortErr(string msg) { if (string.IsNullOrEmpty(msg)) return "表达式错误"; // 取第一句,去掉调用堆栈类的英文噪音 int i = msg.IndexOf(" at System", StringComparison.Ordinal); string s = i > 0 ? msg.Substring(0, i) : msg; i = s.IndexOf('。'); if (i > 0 && i < s.Length) s = s.Substring(0, i); return s.Length > 160 ? s.Substring(0, 160) : s; } // 常用表达式速查(名称, 表达式, 说明) public static readonly string[][] Common = new string[][] { new[]{ "手机号(大陆)", @"1[3-9]\d{9}", "13x-19x 开头 11 位" }, new[]{ "邮箱", @"[\w.+-]+@[\w-]+\.[\w.]+", "常规邮箱格式" }, new[]{ "整数", @"-?\d+", "带可选负号" }, new[]{ "小数", @"-?\d+(\.\d+)?", "整数或小数" }, new[]{ "网址URL", @"https?://[^\s]+", "http/https 开头" }, new[]{ "IPv4", @"\b(?:\d{1,3}\.){3}\d{1,3}\b", "点分十进制(未校验范围)" }, new[]{ "日期(年-月-日)", @"\d{4}-\d{2}-\d{2}", "如 2026-10-21" }, new[]{ "中文汉字", @"[\u4e00-\u9fa5]+", "连续汉字串" }, new[]{ "空白/空行", @"^\s*$", "配合 Multiline 找空行" }, new[]{ "18位身份证", @"\b\d{17}[\dXx]\b", "含末位校验位 X" }, new[]{ "千分位数字", @"\d{1,3}(,\d{3})+", "如 1,234,567" }, new[]{ "HTML标签", @"]*>", "简易标签匹配" }, }; // 替换语法速查 public static readonly string[][] ReplaceSyntax = new string[][] { new[]{ "$0", "整个匹配" }, new[]{ "$1", "第 1 个捕获组" }, new[]{ "${name}", "命名捕获组" }, new[]{ "$$", "字面 $" }, }; } // ---------- 界面层 ---------- public class MainForm : Form { private TextBox _pattern; private CheckBox _ic, _ml, _sl; private TextBox _input, _output, _replace; private ListView _list; private Label _status; private Button _btnFind, _btnRep, _btnClear; public MainForm() { Text = "正则表达式测试器 - getgreentool.com"; Font = new Font("Microsoft YaHei UI", 9F); ClientSize = new Size(860, 620); StartPosition = FormStartPosition.CenterScreen; var lp = new Label { Text = "正则表达式:", AutoSize = true, Location = new Point(10, 14) }; _pattern = new TextBox { Font = new Font("Consolas", 10.5F), Location = new Point(90, 10), Size = new Size(560, 26), Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right }; _btnFind = new Button { Text = "查找匹配 (F5)", Location = new Point(660, 9), Size = new Size(90, 27), Anchor = AnchorStyles.Top | AnchorStyles.Right }; _btnRep = new Button { Text = "全部替换", Location = new Point(756, 9), Size = new Size(90, 27), Anchor = AnchorStyles.Top | AnchorStyles.Right }; _ic = new CheckBox { Text = "忽略大小写", AutoSize = true, Location = new Point(90, 42) }; _ml = new CheckBox { Text = "多行模式 ^$按行", AutoSize = true, Location = new Point(190, 42) }; _sl = new CheckBox { Text = "单行模式 .含换行", AutoSize = true, Location = new Point(330, 42) }; var li = new Label { Text = "测试文本:", AutoSize = true, Location = new Point(10, 74) }; _input = new TextBox { Multiline = true, ScrollBars = ScrollBars.Both, Font = new Font("Consolas", 10F), WordWrap = false, Location = new Point(10, 96), Size = new Size(420, 220), Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom }; var ll = new Label { Text = "匹配结果(点击查看捕获组):", AutoSize = true, Location = new Point(442, 74) }; _list = new ListView { View = View.Details, FullRowSelect = true, Location = new Point(442, 96), Size = new Size(404, 220), Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom }; _list.Columns.Add("#", 34); _list.Columns.Add("位置", 52); _list.Columns.Add("内容", 280); var lr = new Label { Text = "替换为(支持 $1、${name}):", AutoSize = true, Location = new Point(10, 326) }; _replace = new TextBox { Font = new Font("Consolas", 10F), Location = new Point(200, 322), Size = new Size(246, 26), Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right }; _btnClear = new Button { Text = "清空", Location = new Point(10, 320), Size = new Size(60, 28) }; var lo = new Label { Text = "结果:", AutoSize = true, Location = new Point(10, 356) }; _output = new TextBox { Multiline = true, ScrollBars = ScrollBars.Both, ReadOnly = true, BackColor = Color.White, Font = new Font("Consolas", 10F), WordWrap = false, Location = new Point(10, 378), Size = new Size(836, 196), Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom }; _status = new Label { AutoSize = true, Location = new Point(10, 584), ForeColor = Color.DimGray }; // 常用表达式速查(右侧可点) var lc = new Label { Text = "常用:", AutoSize = true, Location = new Point(442, 42) }; int cx = 490; string[][] top4 = new string[][] { RegexOps.Common[0], RegexOps.Common[1], RegexOps.Common[4], RegexOps.Common[7] }; foreach (var c in top4) { var b = new LinkLabel { Text = c[0], AutoSize = true, Location = new Point(cx, 43), Tag = c[1] }; b.LinkClicked += (s, e) => { _pattern.Text = (string)((LinkLabel)s).Tag; DoFind(); }; Controls.Add(b); cx += 12 + TextRenderer.MeasureText(c[0], Font).Width; } Controls.AddRange(new Control[] { lp, _pattern, _btnFind, _btnRep, _ic, _ml, _sl, lc, li, _input, ll, _list, lr, _replace, _btnClear, lo, _output, _status }); AcceptButton = _btnFind; _btnFind.Click += (s, e) => DoFind(); _btnRep.Click += (s, e) => DoReplace(); _btnClear.Click += (s, e) => { _input.Clear(); _output.Clear(); _list.Items.Clear(); _status.Text = "已清空。"; }; _list.SelectedIndexChanged += (s, e) => { if (_list.SelectedItems.Count == 0) return; var tag = _list.SelectedItems[0].Tag as string[]; if (tag != null) _output.Text = tag[0]; }; // 预填示例 _pattern.Text = @"[\w.+-]+@[\w-]+\.[\w.]+"; _input.Text = "联系 support@greentool.com 或 sales@example.cn,备用 admin@test.io"; DoFind(); } private RegexOptions Opt { get { return RegexOps.BuildOptions(_ic.Checked, _ml.Checked, _sl.Checked); } } private void DoFind() { string err; var ms = RegexOps.FindAll(_pattern.Text, _input.Text, Opt, out err); _list.Items.Clear(); if (err != null) { _output.Text = "✗ " + err; _status.Text = "表达式有误"; _status.ForeColor = Color.Firebrick; return; } _status.ForeColor = Color.DimGray; _status.Text = "共 " + ms.Count + " 处匹配" + (ms.Count >= 500 ? "(已达显示上限 500)" : ""); var sb = new StringBuilder(); for (int i = 0; i < ms.Count; i++) { var m = ms[i]; var it = new ListViewItem((i + 1).ToString(CultureInfo.InvariantCulture)); it.SubItems.Add(m.Index.ToString(CultureInfo.InvariantCulture)); it.SubItems.Add(m.Length > 120 ? m.Value.Substring(0, 120) + "…" : m.Value); string[] gdesc = DescribeGroups(m); it.Tag = new string[] { "第 " + (i + 1) + " 处 @ 位置 " + m.Index + ",长度 " + m.Length + "\r\n匹配:" + m.Value + (gdesc.Length > 0 ? "\r\n" + gdesc[0] : "") }; _list.Items.Add(it); sb.AppendLine((i + 1) + ". [" + m.Index + "+" + m.Length + "] " + m.Value); } _output.Text = sb.Length > 0 ? sb.ToString().TrimEnd() : "(无匹配)"; } private string[] DescribeGroups(RegexOps.MatchInfo m) { var parts = new List(); for (int i = 0; i < m.Groups.Length; i++) parts.Add("组" + (i + 1) + (m.Groups[i] == null ? "(未参与)" : "=\"" + m.Groups[i] + "\"")); return parts.Count > 0 ? new string[] { string.Join(",", parts) } : new string[0]; } private void DoReplace() { string err; int n = RegexOps.ReplaceCount(_pattern.Text, _input.Text, Opt, out err); if (err != null) { _output.Text = "✗ " + err; return; } string result = RegexOps.Replace(_pattern.Text, _input.Text, _replace.Text, Opt, out err); if (err != null) { _output.Text = "✗ " + err; return; } _input.Text = result; _output.Text = "✓ 已替换 " + n + " 处,替换后的文本已放入上方文本框。\r\n" + (result.Length > 800 ? result.Substring(0, 800) + "…" : result); _status.Text = "替换 " + n + " 处完成。"; DoFind(); } } // ---------- 自测 ---------- public static class SelfTest { private static int _fail; private static void Check(bool ok, string name) { if (!ok) { _fail++; Console.WriteLine("FAIL " + name); } } private static RegexOptions O { get { return RegexOptions.None; } } private static List M(string p, string s) { string e; return RegexOps.FindAll(p, s, O, out e); } private static string Rep(string p, string s, string r) { string e; return RegexOps.Replace(p, s, r, O, out e); } public static int RunAll() { _fail = 0; // 基础匹配 var ms = M(@"\d+", "a1b22c333"); Check(ms.Count == 3 && ms[0].Value == "1" && ms[2].Value == "333", "数字匹配3处"); Check(ms[2].Index == 6 && ms[2].Length == 3, "位置与长度"); // 校验错误 Check(RegexOps.Validate("(") != null, "括号不闭合报错"); Check(RegexOps.Validate(@"\d+") == null, "合法表达式无错"); Check(RegexOps.Validate("") != null, "空表达式报错"); Check(RegexOps.Validate("[a-") != null, "字符类不闭合报错"); Check(RegexOps.Validate(@"(?a)") == null, "命名组合法"); Check(RegexOps.Validate("(?a") != null, "命名组不闭合报错"); // 错误信息可用(含位置或可读描述) string e1; RegexOps.FindAll("(bar", "test", O, out e1); Check(e1 != null && e1.Length > 0 && !e1.Contains("at System"), "错误信息可读无堆栈"); // 选项 string e; var r1 = RegexOps.FindAll("abc", "ABCabc", RegexOps.BuildOptions(true, false, false), out e); Check(r1.Count == 2, "忽略大小写2处"); var r2 = RegexOps.FindAll("abc", "ABCabc", O, out e); Check(r2.Count == 1, "区分大小写1处"); var r3 = RegexOps.FindAll("^a", "a\na", RegexOps.BuildOptions(false, true, false), out e); Check(r3.Count == 2, "多行模式^每行生效"); var r4 = RegexOps.FindAll("^a", "a\na", O, out e); Check(r4.Count == 1, "默认^仅串首"); var r5 = RegexOps.FindAll("a.b", "a\nb", RegexOps.BuildOptions(false, false, true), out e); Check(r5.Count == 1, "单行模式.含换行"); var r6 = RegexOps.FindAll("a.b", "a\nb", O, out e); Check(r6.Count == 0, "默认.不含换行"); // 捕获组 var g = M(@"(\d{4})-(\d{2})", "日期 2026-10 与 2027-03"); Check(g.Count == 2 && g[0].Groups[0] == "2026" && g[0].Groups[1] == "10", "两组捕获正确"); var ng = M(@"(?\d{4})-(?\d{2})", "2026-10"); Check(ng[0].Groups[0] == "2026" && ng[0].Groups[1] == "10", "命名组捕获"); // 未参与的组 var opt = M(@"(a)|(z)", "ab"); Check(opt.Count == 1 && opt[0].Groups[0] == "a" && opt[0].Groups[1] == null, "未参与组为null"); // 替换 Check(Rep(@"(\w+)@example\.com", "a@example.com b@example.com", "$1@new.io") == "a@new.io b@new.io", "替换引用组1"); Check(Rep(@"\s+", "a b\t c", " ") == "a b c", "空白归一"); string e2; int n = RegexOps.ReplaceCount(@"\d+", "a1b22c333", O, out e2); Check(n == 3 && e2 == null, "替换计数3"); Check(Rep("x", "abc", "y") == "abc", "无匹配替换原样"); // 替换语法 Check(Rep("foo", "foo", "$$100") == "$100", "$$转义"); Check(Rep(@"(\d)(\d)", "12", "$2$1") == "21", "组顺序交换"); // 超时保护(灾难性回溯) string e3; RegexOps.FindAll(@"(a+)+$", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaab", O, out e3); Check(e3 != null && e3.Contains("超时"), "回溯超时被拦截"); // 500 上限 var many = M(@"\d", new string('1', 600)); Check(many.Count == 500, "结果上限500"); // 常用表达式的正确性抽查 Check(M(RegexOps.Common[0][1], "13812345678 12345").Count == 1, "手机号命中"); Check(M(RegexOps.Common[0][1], "12812345678").Count == 0, "手机号128不命中"); Check(M(RegexOps.Common[1][1], "a@b.cn").Count == 1, "邮箱命中"); Check(M(RegexOps.Common[6][1], "2026-10-21 ok").Count == 1, "日期命中"); Check(M(RegexOps.Common[7][1], "你好世界 hi").Count == 1, "中文命中"); Check(M(RegexOps.Common[10][1], "1,234,567 元").Count == 1, "千分位命中"); Check(M(RegexOps.Common[9][1], "110101199003077658").Count == 1, "18位身份证命中"); Check(M(RegexOps.Common[5][1], "192.168.1.1").Count == 1, "IPv4命中"); // 空输入安全 var empty = M(@"\d", ""); Check(empty.Count == 0, "空输入无崩溃"); var nl = M(@"^$", "a\n\nb", RegexOptions.Multiline); Check(nl.Count == 1, "空行匹配a\\n\\nb中1处"); // 单词边界 Check(M(@"\bcat\b", "cat catalog cat").Count == 2, "词边界"); Console.WriteLine("SelfTest: " + _fail + " failed"); return _fail == 0 ? 0 : 1; } private static List M(string p, string s, RegexOptions o) { string e; return RegexOps.FindAll(p, s, o, out e); } private static void _unused() { M("a", "b", RegexOptions.None); } } public static class RegexProgram { [STAThread] public static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(SelfTest.RunAll()); } Application.EnableVisualStyles(); Application.Run(new MainForm()); } } }