NewLife/XCoder

feat(RegexTool): 增强正则表达式工具,支持匹配结果按行列出,选中行高亮原文并联动分组与捕获
大石头 authored at 2026-11-14 01:03:42
f446b16
Tree
1 Parent(s) 61cac2b
Summary: 19 changed files with 574 additions and 33 deletions.
Modified +1 -1
Added +140 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +4 -0
Modified +6 -0
Modified +12 -0
Modified +3 -0
Added +15 -0
Modified +10 -3
Modified +119 -9
Modified +228 -20
Modified +1 -1
diff --git "a/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md" "b/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md"
index a5e5031..8e00111 100644
--- "a/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md"
+++ "b/Doc/\345\212\237\350\203\275\346\270\205\345\215\225.md"
@@ -75,7 +75,7 @@
 
 | 编码 | 功能 | 类型 | 实现 | 测试 | 注释 | 说明 |
 |------|------|:----:|:----:|:----:|:----:|------|
-| DEV-7 | 正则表达式(匹配/替换/捕获组/右键模板) | 前端+逻辑 | ✅ | ✅ | ✅ | 匹配/替换/捕获组+2 秒超时;正则框与输入框右键可插入正则模板/测试内容模板(内置 13 个模板,带 # 注释的模板自动启用忽略空白);15 项单测 + 1 项无头 UI 测试 |
+| DEV-7 | 正则表达式(匹配/替换/捕获组/右键模板) | 前端+逻辑 | ✅ | ✅ | ✅ | 匹配结果按行表格列出(序号/值/行/索引/长度),选中行自动高亮原文;右侧分组表显示组号/组名/值/成功标记,选中分组再展开多次捕获,捕获行同样联动高亮原文;替换结果写入右侧结果框;2 秒超时;正则框与输入框右键可插入正则模板/测试内容模板(内置 13 个模板,带 # 注释的模板自动启用忽略空白);15 项单测 + 4 项无头 UI 测试 |
 | DEV-8 | 加密解密(摘要/编码/RSA/URL 等 34 命令) | 前端+逻辑 | ✅ | ✅ | ✅ | 34 个命令(摘要 8 / 带密钥摘要 4 / 编码 12 / RSA 4 / 实用 6),左侧命令栏 + 搜索过滤 + 原文/密码/结果纵向流水线;原文与密码均支持字符串/HEX/Base64,结果按三种表示分组并可单条回填原文,上下互换自动切换输入格式;25 项单测 + 3 项无头 UI 测试 |
 | DEV-9 | 对称加密(AES/DES 等) | 前端+逻辑 | ✅ | ✅ | ✅ | AES-256 / DES,CBC+PKCS7;5 项单测 |
 | DEV-10 | MD5 解密(本地优先 + 在线接口) | 前端+逻辑 | ✅ | ✅ | ✅ | 本地常用表 + 在线反查(适配站点新页面结构、带 UA,实测命中 hello world);离线时自动回退;8 项单测 |
Added +140 -0
diff --git a/Tests/XCoder.App.UiTests/RegexToolViewTests.cs b/Tests/XCoder.App.UiTests/RegexToolViewTests.cs
new file mode 100644
index 0000000..8df0561
--- /dev/null
+++ b/Tests/XCoder.App.UiTests/RegexToolViewTests.cs
@@ -0,0 +1,140 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Threading.Tasks;
+using Avalonia;
+using Avalonia.Controls;
+using NewLife.XCoder.Models;
+using NewLife.XCoder.Tools.Regex;
+using Xunit;
+
+namespace XCoder.App.UiTests;
+
+/// <summary>正则工具:匹配结果表格、选中联动与捕获展开</summary>
+public class RegexToolViewTests
+{
+    private static RegexToolView CreateView()
+    {
+        var view = new RegexToolView();
+        view.Measure(new Size(1200, 900));
+        view.Arrange(new Rect(0, 0, 1200, 900));
+
+        return view;
+    }
+
+    private static List<T> Items<T>(ListBox list) => list.ItemsSource?.Cast<T>().ToList() ?? [];
+
+    [Fact]
+    [DisplayName("匹配结果按行列出,选中匹配行高亮原文并联动分组与捕获")]
+    public async Task Match_Rows_And_Selection_Drilldown()
+    {
+        await UiSession.Run(async () =>
+        {
+            var view = CreateView();
+            var pattern = view.FindControl<TextBox>("PatternBox")!;
+            var input = view.FindControl<TextBox>("InputBox")!;
+            var matchList = view.FindControl<ListBox>("MatchList")!;
+            var groupList = view.FindControl<ListBox>("GroupList")!;
+            var captureList = view.FindControl<ListBox>("CaptureList")!;
+
+            pattern.Text = @"(?<word>[A-Za-z]+)-(\d+)";
+            input.Text = "abc-12\nde-3";
+            var count = await view.RunMatchAsync();
+
+            Assert.Equal(2, count);
+            Assert.Equal(2, matchList.ItemCount);
+
+            var matches = Items<RegexMatchItem>(matchList);
+            Assert.Equal("abc-12", matches[0].Value);
+            Assert.Equal(1, matches[0].Line);
+            Assert.Equal(0, matches[0].Position);
+            Assert.Equal(6, matches[0].Length);
+            Assert.Equal(2, matches[1].Line);
+
+            // 选中第一项:原文高亮 + 右侧分组表刷新
+            matchList.SelectedIndex = 0;
+            Assert.Equal(0, input.SelectionStart);
+            Assert.Equal(6, input.SelectionEnd);
+
+            var groups = Items<RegexGroupItem>(groupList);
+            Assert.Equal(3, groups.Count);
+            Assert.Equal("word", groups[1].Name);
+            Assert.Equal("abc", groups[1].Value);
+            Assert.Equal(1, groupList.SelectedIndex);
+
+            // 选中第二组:原文选中数字片段 + 捕获表出现
+            groupList.SelectedIndex = 2;
+            Assert.Equal(4, input.SelectionStart);
+            Assert.Equal(6, input.SelectionEnd);
+
+            var captures = Items<RegexCaptureItem>(captureList);
+            Assert.Single(captures);
+            Assert.Equal("12", captures[0].Value);
+        });
+    }
+
+    [Fact]
+    [DisplayName("重复分组展开全部捕获,选中捕获行高亮对应片段")]
+    public async Task Group_Captures_Expand()
+    {
+        await UiSession.Run(async () =>
+        {
+            var view = CreateView();
+            var pattern = view.FindControl<TextBox>("PatternBox")!;
+            var input = view.FindControl<TextBox>("InputBox")!;
+            var matchList = view.FindControl<ListBox>("MatchList")!;
+            var groupList = view.FindControl<ListBox>("GroupList")!;
+            var captureList = view.FindControl<ListBox>("CaptureList")!;
+
+            pattern.Text = @"(\w)+";
+            input.Text = "abc";
+            await view.RunMatchAsync();
+
+            matchList.SelectedIndex = 0;
+            groupList.SelectedIndex = 1;
+
+            var captures = Items<RegexCaptureItem>(captureList);
+            Assert.Equal(3, captures.Count);
+            String[] expected = ["a", "b", "c"];
+            Assert.Equal(expected, captures.Select(e => e.Value).ToArray());
+
+            captureList.SelectedIndex = 0;
+            Assert.Equal(0, input.SelectionStart);
+            Assert.Equal(1, input.SelectionEnd);
+        });
+    }
+
+    [Fact]
+    [DisplayName("可选分组未命中时标记失败,替换结果写入结果框")]
+    public async Task FailedGroup_And_Replace()
+    {
+        await UiSession.Run(async () =>
+        {
+            var view = CreateView();
+            var pattern = view.FindControl<TextBox>("PatternBox")!;
+            var input = view.FindControl<TextBox>("InputBox")!;
+            var replacement = view.FindControl<TextBox>("ReplacementBox")!;
+            var output = view.FindControl<TextBox>("OutputBox")!;
+            var matchList = view.FindControl<ListBox>("MatchList")!;
+            var groupList = view.FindControl<ListBox>("GroupList")!;
+
+            pattern.Text = @"(a)?(b)";
+            input.Text = "b";
+            replacement.Text = "[$2]";
+
+            var count = await view.RunReplaceAsync();
+
+            Assert.Equal(1, count);
+            Assert.Equal("[b]", output.Text);
+            Assert.Equal(1, matchList.ItemCount);
+
+            matchList.SelectedIndex = 0;
+            var groups = Items<RegexGroupItem>(groupList);
+            Assert.False(groups[1].Success);
+            Assert.Equal("—", groups[1].SuccessText);
+            Assert.True(groups[2].Success);
+            Assert.Equal("b", groups[2].Value);
+        });
+    }
+}
Modified +4 -0
diff --git a/XCoder.App/Locales/ar.yml b/XCoder.App/Locales/ar.yml
index f06c3ed..4c027cd 100644
--- a/XCoder.App/Locales/ar.yml
+++ b/XCoder.App/Locales/ar.yml
@@ -1022,3 +1022,7 @@
 "Pattern templates": "قوالب التعبيرات النمطية"
 "Sample texts": "نصوص اختبارية"
 "Right-click the pattern or input box to insert templates": "انقر بزر الماوس الأيمن على النمط أو حقل الإدخال لإدراج قالب"
+"Index": "الفهرس"
+"Line": "السطر"
+"Success": "نجاح"
+"Value": "القيمة"
Modified +4 -0
diff --git a/XCoder.App/Locales/de.yml b/XCoder.App/Locales/de.yml
index ee1717c..196bdfc 100644
--- a/XCoder.App/Locales/de.yml
+++ b/XCoder.App/Locales/de.yml
@@ -1022,3 +1022,7 @@
 "Pattern templates": "Regex-Vorlagen"
 "Sample texts": "Beispieltexte"
 "Right-click the pattern or input box to insert templates": "Rechtsklick auf Muster oder Eingabe fügt Vorlagen ein"
+"Index": "Index"
+"Line": "Zeile"
+"Success": "Erfolg"
+"Value": "Wert"
Modified +4 -0
diff --git a/XCoder.App/Locales/es.yml b/XCoder.App/Locales/es.yml
index 1e3bc6c..30edd8f 100644
--- a/XCoder.App/Locales/es.yml
+++ b/XCoder.App/Locales/es.yml
@@ -1022,3 +1022,7 @@
 "Pattern templates": "Plantillas de expresión"
 "Sample texts": "Textos de ejemplo"
 "Right-click the pattern or input box to insert templates": "Haz clic derecho en el patrón o en el cuadro de entrada para insertar plantillas"
+"Index": "Índice"
+"Line": "Línea"
+"Success": "Éxito"
+"Value": "Valor"
Modified +4 -0
diff --git a/XCoder.App/Locales/fr.yml b/XCoder.App/Locales/fr.yml
index 09815e2..d656dba 100644
--- a/XCoder.App/Locales/fr.yml
+++ b/XCoder.App/Locales/fr.yml
@@ -1022,3 +1022,7 @@
 "Pattern templates": "Modèles d'expressions"
 "Sample texts": "Textes d'exemple"
 "Right-click the pattern or input box to insert templates": "Clic droit sur le motif ou la zone de saisie pour insérer un modèle"
+"Index": "Index"
+"Line": "Ligne"
+"Success": "Succès"
+"Value": "Valeur"
Modified +4 -0
diff --git a/XCoder.App/Locales/ja.yml b/XCoder.App/Locales/ja.yml
index 5154ebb..aec6d5a 100644
--- a/XCoder.App/Locales/ja.yml
+++ b/XCoder.App/Locales/ja.yml
@@ -1022,3 +1022,7 @@
 "Pattern templates": "正規表現テンプレート"
 "Sample texts": "テストテキスト"
 "Right-click the pattern or input box to insert templates": "正規表現または入力欄を右クリックするとテンプレートを挿入できます"
+"Index": "インデックス"
+"Line": "行"
+"Success": "成功"
+"Value": "値"
Modified +4 -0
diff --git a/XCoder.App/Locales/ko.yml b/XCoder.App/Locales/ko.yml
index babf7c8..e2cdafe 100644
--- a/XCoder.App/Locales/ko.yml
+++ b/XCoder.App/Locales/ko.yml
@@ -1023,3 +1023,7 @@
 "Pattern templates": "정규식 템플릿"
 "Sample texts": "테스트 텍스트"
 "Right-click the pattern or input box to insert templates": "정규식 또는 입력란을 마우스 오른쪽 단추로 클릭하면 템플릿을 삽입할 수 있습니다"
+"Index": "인덱스"
+"Line": "행"
+"Success": "성공"
+"Value": "값"
Modified +4 -0
diff --git a/XCoder.App/Locales/pt.yml b/XCoder.App/Locales/pt.yml
index 30fc4fc..399ff34 100644
--- a/XCoder.App/Locales/pt.yml
+++ b/XCoder.App/Locales/pt.yml
@@ -1022,3 +1022,7 @@
 "Pattern templates": "Modelos de expressão"
 "Sample texts": "Textos de exemplo"
 "Right-click the pattern or input box to insert templates": "Clique com o botão direito no padrão ou na caixa de entrada para inserir modelos"
+"Index": "Índice"
+"Line": "Linha"
+"Success": "Sucesso"
+"Value": "Valor"
Modified +4 -0
diff --git a/XCoder.App/Locales/ru.yml b/XCoder.App/Locales/ru.yml
index a89c88c..0028a84 100644
--- a/XCoder.App/Locales/ru.yml
+++ b/XCoder.App/Locales/ru.yml
@@ -1022,3 +1022,7 @@
 "Pattern templates": "Шаблоны регулярных выражений"
 "Sample texts": "Тестовые тексты"
 "Right-click the pattern or input box to insert templates": "Щёлкните правой кнопкой по выражению или полю ввода, чтобы вставить шаблон"
+"Index": "Индекс"
+"Line": "Строка"
+"Success": "Успех"
+"Value": "Значение"
Modified +4 -0
diff --git a/XCoder.App/Locales/zh-Hans.yml b/XCoder.App/Locales/zh-Hans.yml
index 42c9684..15ec685 100644
--- a/XCoder.App/Locales/zh-Hans.yml
+++ b/XCoder.App/Locales/zh-Hans.yml
@@ -1023,3 +1023,7 @@
 "Pattern templates": "正则模板"
 "Sample texts": "测试内容"
 "Right-click the pattern or input box to insert templates": "右键正则表达式或输入框可插入模板"
+"Index": "索引"
+"Line": "行"
+"Success": "成功"
+"Value": "值"
Modified +4 -0
diff --git a/XCoder.App/Locales/zh-Hant.yml b/XCoder.App/Locales/zh-Hant.yml
index 03b71a5..648e595 100644
--- a/XCoder.App/Locales/zh-Hant.yml
+++ b/XCoder.App/Locales/zh-Hant.yml
@@ -1023,3 +1023,7 @@
 "Pattern templates": "正則模板"
 "Sample texts": "測試內容"
 "Right-click the pattern or input box to insert templates": "在正則表示式或輸入框上按右鍵可插入模板"
+"Index": "索引"
+"Line": "行"
+"Success": "成功"
+"Value": "值"
Modified +6 -0
diff --git a/XCoder.App/Models/RegexCaptureItem.cs b/XCoder.App/Models/RegexCaptureItem.cs
index a9fd9e5..53f8b83 100644
--- a/XCoder.App/Models/RegexCaptureItem.cs
+++ b/XCoder.App/Models/RegexCaptureItem.cs
@@ -11,6 +11,9 @@ public class RegexCaptureItem
     /// <summary>值</summary>
     public String Value { get; set; } = "";
 
+    /// <summary>行号</summary>
+    public Int32 Line { get; set; }
+
     /// <summary>位置</summary>
     public Int32 Position { get; set; }
 
@@ -20,6 +23,9 @@ public class RegexCaptureItem
     /// <summary>位置描述</summary>
     public String Location => $"({Position},{Length})";
 
+    /// <summary>单行显示值(转义换行与制表符)</summary>
+    public String Display => RegexTextHelper.Escape(Value);
+
     /// <summary>原始 Capture 对象</summary>
     public Capture? Capture { get; set; }
 }
Modified +12 -0
diff --git a/XCoder.App/Models/RegexGroupItem.cs b/XCoder.App/Models/RegexGroupItem.cs
index 20cf028..66ceee3 100644
--- a/XCoder.App/Models/RegexGroupItem.cs
+++ b/XCoder.App/Models/RegexGroupItem.cs
@@ -14,15 +14,27 @@ public class RegexGroupItem
     /// <summary>值</summary>
     public String Value { get; set; } = "";
 
+    /// <summary>行号;未匹配成功时为 0</summary>
+    public Int32 Line { get; set; }
+
     /// <summary>位置</summary>
     public Int32 Position { get; set; }
 
     /// <summary>长度</summary>
     public Int32 Length { get; set; }
 
+    /// <summary>是否匹配成功(可选分组未命中时为 false)</summary>
+    public Boolean Success { get; set; }
+
     /// <summary>位置描述</summary>
     public String Location => $"({Position},{Length})";
 
+    /// <summary>单行显示值(转义换行与制表符)</summary>
+    public String Display => RegexTextHelper.Escape(Value);
+
+    /// <summary>成功标记</summary>
+    public String SuccessText => Success ? "✓" : "—";
+
     /// <summary>原始 Group 对象</summary>
     public Group? Group { get; set; }
 }
Modified +3 -0
diff --git a/XCoder.App/Models/RegexMatchItem.cs b/XCoder.App/Models/RegexMatchItem.cs
index a5d4087..69847d4 100644
--- a/XCoder.App/Models/RegexMatchItem.cs
+++ b/XCoder.App/Models/RegexMatchItem.cs
@@ -23,6 +23,9 @@ public class RegexMatchItem
     /// <summary>位置描述</summary>
     public String Location => $"({Line},{Position},{Length})";
 
+    /// <summary>单行显示值(转义换行与制表符)</summary>
+    public String Display => RegexTextHelper.Escape(Value);
+
     /// <summary>原始 Match 对象</summary>
     public Match? Match { get; set; }
 }
Added +15 -0
diff --git a/XCoder.App/Models/RegexTextHelper.cs b/XCoder.App/Models/RegexTextHelper.cs
new file mode 100644
index 0000000..ad7d0a3
--- /dev/null
+++ b/XCoder.App/Models/RegexTextHelper.cs
@@ -0,0 +1,15 @@
+namespace NewLife.XCoder.Models;
+
+/// <summary>正则结果文本显示辅助</summary>
+internal static class RegexTextHelper
+{
+    /// <summary>转义换行、回车与制表符,避免表格行被撑成多行</summary>
+    /// <param name="value">原始文本</param>
+    /// <returns>单行显示文本</returns>
+    public static String Escape(String value)
+    {
+        if (String.IsNullOrEmpty(value)) return "";
+
+        return value.Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", "\\t");
+    }
+}
Modified +10 -3
diff --git a/XCoder.App/Tools/Regex/RegexService.cs b/XCoder.App/Tools/Regex/RegexService.cs
index a53346c..69db7a1 100644
--- a/XCoder.App/Tools/Regex/RegexService.cs
+++ b/XCoder.App/Tools/Regex/RegexService.cs
@@ -23,7 +23,7 @@ public static class RegexService
         if (input == null) throw new ArgumentNullException(nameof(input));
         if (pattern == null) throw new ArgumentNullException(nameof(pattern));
 
-        var regex = CreateRegex(pattern, options, 0);
+        var regex = Create(pattern, options);
         var list = new List<RegexMatchResult>();
         foreach (Match match in regex.Matches(input))
         {
@@ -45,13 +45,20 @@ public static class RegexService
         if (input == null) throw new ArgumentNullException(nameof(input));
         if (pattern == null) throw new ArgumentNullException(nameof(pattern));
 
-        var regex = CreateRegex(pattern, options, 0);
+        var regex = Create(pattern, options);
 
         return regex.Replace(input, replacement ?? "");
     }
 
-    private static System.Text.RegularExpressions.Regex CreateRegex(String pattern, RegexOptions options, Int32 timeoutSeconds)
+    /// <summary>创建带 2 秒超时保护的正则对象</summary>
+    /// <param name="pattern">表达式</param>
+    /// <param name="options">选项</param>
+    /// <returns>正则对象</returns>
+    /// <exception cref="ArgumentException">表达式非法</exception>
+    public static System.Text.RegularExpressions.Regex Create(String pattern, RegexOptions options = RegexOptions.None)
     {
+        if (pattern == null) throw new ArgumentNullException(nameof(pattern));
+
         try
         {
             // 加超时,避免灾难性回溯卡死界面
Modified +119 -9
diff --git a/XCoder.App/Tools/Regex/RegexToolView.axaml b/XCoder.App/Tools/Regex/RegexToolView.axaml
index 75b4af2..a512b47 100644
--- a/XCoder.App/Tools/Regex/RegexToolView.axaml
+++ b/XCoder.App/Tools/Regex/RegexToolView.axaml
@@ -1,7 +1,38 @@
 <UserControl xmlns="https://github.com/avaloniaui"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:loc="using:NewLife.XCoder.Services"
+             xmlns:models="using:NewLife.XCoder.Models"
              x:Class="NewLife.XCoder.Tools.Regex.RegexToolView">
+    <UserControl.Styles>
+        <Style Selector="ListBox.ResultTable">
+            <Setter Property="CornerRadius" Value="8" />
+            <Setter Property="Padding" Value="0" />
+        </Style>
+        <Style Selector="ListBox.ResultTable ListBoxItem">
+            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
+            <Setter Property="Padding" Value="8,4" />
+            <Setter Property="MinHeight" Value="26" />
+        </Style>
+        <Style Selector="TextBlock.tableHeader">
+            <Setter Property="FontSize" Value="11" />
+            <Setter Property="FontWeight" Value="SemiBold" />
+            <Setter Property="Foreground" Value="{DynamicResource TextTertiary}" />
+            <Setter Property="Margin" Value="8,0" />
+            <Setter Property="VerticalAlignment" Value="Center" />
+        </Style>
+        <Style Selector="TextBlock.cell">
+            <Setter Property="FontSize" Value="12" />
+            <Setter Property="TextTrimming" Value="CharacterEllipsis" />
+            <Setter Property="VerticalAlignment" Value="Center" />
+        </Style>
+        <Style Selector="TextBlock.cellNum">
+            <Setter Property="FontSize" Value="12" />
+            <Setter Property="Foreground" Value="{DynamicResource TextSecondary}" />
+            <Setter Property="HorizontalAlignment" Value="Right" />
+            <Setter Property="VerticalAlignment" Value="Center" />
+        </Style>
+    </UserControl.Styles>
+
     <ScrollViewer Name="PageScroll" Margin="20"
                   HorizontalScrollBarVisibility="Disabled"
                   VerticalScrollBarVisibility="Auto">
@@ -13,10 +44,10 @@
                 <TextBlock Text="{loc:Tr 'Right-click the pattern or input box to insert templates'}" Classes="dim" TextWrapping="Wrap" />
             </StackPanel>
 
-            <Border Grid.Row="1" Classes="panel" Padding="16" MinHeight="240">
-                <Grid RowDefinitions="Auto,Auto,*,Auto" RowSpacing="10">
+            <Border Grid.Row="1" Classes="panel" Padding="16" MinHeight="560">
+                <Grid RowDefinitions="Auto,Auto,*,Auto,Auto" RowSpacing="10">
                     <Grid ColumnDefinitions="*,Auto" ColumnSpacing="8">
-                        <TextBox Name="PatternBox" AcceptsReturn="True" AcceptsTab="True" MinHeight="90"
+                        <TextBox Name="PatternBox" AcceptsReturn="True" AcceptsTab="True" MinHeight="72"
                                  TextWrapping="NoWrap" FontFamily="{DynamicResource FontMono}"
                                  PlaceholderText="{loc:Tr 'Regular expression, e.g. ([0-9]{4})-([0-9]{2})-([0-9]{2})'}" />
                         <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="6" VerticalAlignment="Top">
@@ -31,23 +62,102 @@
                         <CheckBox Name="SinglelineBox" Content="{loc:Tr 'Single-line mode'}" FontSize="12" Margin="0,0,14,6" />
                         <CheckBox Name="IgnorePatternWhitespaceBox" Content="{loc:Tr 'Ignore whitespace'}" FontSize="12" Margin="0,0,14,6" />
                         <TextBlock Text="{loc:Tr 'Replacement (supports $1)'}" Classes="dim" VerticalAlignment="Center" Margin="0,0,6,6" />
-                        <TextBox Name="ReplacementBox" Width="240" Margin="0,0,0,6" PlaceholderText="$1/$2/$3" />
+                        <TextBox Name="ReplacementBox" Width="220" Margin="0,0,0,6" PlaceholderText="$1/$2/$3" />
                     </WrapPanel>
 
-                    <Grid Grid.Row="2" ColumnDefinitions="*,*" ColumnSpacing="12">
+                    <Grid Grid.Row="2" ColumnDefinitions="*,*" ColumnSpacing="12" MinHeight="170">
                         <Grid RowDefinitions="Auto,*" RowSpacing="6">
                             <TextBlock Text="{loc:Tr 'Input text'}" FontWeight="SemiBold" />
-                            <TextBox Grid.Row="1" Name="InputBox" AcceptsReturn="True" MinHeight="160"
-                                     TextWrapping="Wrap" PlaceholderText="{loc:Tr 'Paste text to match'}" />
+                            <TextBox Grid.Row="1" Name="InputBox" AcceptsReturn="True" AcceptsTab="True" MinHeight="170"
+                                     TextWrapping="Wrap" FontFamily="{DynamicResource FontMono}"
+                                     ClearSelectionOnLostFocus="False"
+                                     IsInactiveSelectionHighlightEnabled="True"
+                                     PlaceholderText="{loc:Tr 'Paste text to match'}" />
                         </Grid>
                         <Grid Grid.Column="1" RowDefinitions="Auto,*" RowSpacing="6">
                             <TextBlock Text="{loc:Tr 'Result'}" FontWeight="SemiBold" />
-                            <TextBox Grid.Row="1" Name="OutputBox" AcceptsReturn="True" MinHeight="160"
+                            <TextBox Grid.Row="1" Name="OutputBox" AcceptsReturn="True" MinHeight="170"
                                      TextWrapping="NoWrap" IsReadOnly="True" FontFamily="{DynamicResource FontMono}" />
                         </Grid>
                     </Grid>
 
-                    <TextBlock Grid.Row="3" Name="StatusText" Classes="dim" Text="{loc:Tr 'Waiting'}" />
+                    <Grid Grid.Row="3" ColumnDefinitions="*,4,*" MinHeight="260">
+                        <Grid RowDefinitions="Auto,Auto,*" RowSpacing="4">
+                            <TextBlock Text="{loc:Tr 'Match results'}" FontWeight="SemiBold" />
+                            <Grid Grid.Row="1" ColumnDefinitions="36,*,56,64,56">
+                                <TextBlock Classes="tableHeader" Text="#" />
+                                <TextBlock Grid.Column="1" Classes="tableHeader" Text="{loc:Tr 'Value'}" />
+                                <TextBlock Grid.Column="2" Classes="tableHeader" Text="{loc:Tr 'Line'}" HorizontalAlignment="Right" />
+                                <TextBlock Grid.Column="3" Classes="tableHeader" Text="{loc:Tr 'Index'}" HorizontalAlignment="Right" />
+                                <TextBlock Grid.Column="4" Classes="tableHeader" Text="{loc:Tr 'Length'}" HorizontalAlignment="Right" />
+                            </Grid>
+                            <ListBox Grid.Row="2" Name="MatchList" Classes="ResultTable">
+                                <ListBox.ItemTemplate>
+                                    <DataTemplate x:DataType="models:RegexMatchItem">
+                                        <Grid ColumnDefinitions="36,*,56,64,56">
+                                            <TextBlock Classes="cellNum" HorizontalAlignment="Left" Text="{Binding Index}" />
+                                            <TextBlock Grid.Column="1" Classes="cell" FontFamily="{DynamicResource FontMono}" Text="{Binding Display}" />
+                                            <TextBlock Grid.Column="2" Classes="cellNum" Text="{Binding Line}" />
+                                            <TextBlock Grid.Column="3" Classes="cellNum" Text="{Binding Position}" />
+                                            <TextBlock Grid.Column="4" Classes="cellNum" Text="{Binding Length}" />
+                                        </Grid>
+                                    </DataTemplate>
+                                </ListBox.ItemTemplate>
+                            </ListBox>
+                        </Grid>
+
+                        <Grid Grid.Column="2" RowDefinitions="Auto,Auto,*,Auto,Auto,*" RowSpacing="4">
+                            <TextBlock Text="{loc:Tr 'Group'}" FontWeight="SemiBold" />
+                            <Grid Grid.Row="1" ColumnDefinitions="32,76,*,40,52,46,40">
+                                <TextBlock Classes="tableHeader" Text="#" />
+                                <TextBlock Grid.Column="1" Classes="tableHeader" Text="{loc:Tr 'Name'}" />
+                                <TextBlock Grid.Column="2" Classes="tableHeader" Text="{loc:Tr 'Value'}" />
+                                <TextBlock Grid.Column="3" Classes="tableHeader" Text="{loc:Tr 'Line'}" HorizontalAlignment="Right" />
+                                <TextBlock Grid.Column="4" Classes="tableHeader" Text="{loc:Tr 'Index'}" HorizontalAlignment="Right" />
+                                <TextBlock Grid.Column="5" Classes="tableHeader" Text="{loc:Tr 'Length'}" HorizontalAlignment="Right" />
+                                <TextBlock Grid.Column="6" Classes="tableHeader" Text="{loc:Tr 'Success'}" HorizontalAlignment="Center" />
+                            </Grid>
+                            <ListBox Grid.Row="2" Name="GroupList" Classes="ResultTable">
+                                <ListBox.ItemTemplate>
+                                    <DataTemplate x:DataType="models:RegexGroupItem">
+                                        <Grid ColumnDefinitions="32,76,*,40,52,46,40">
+                                            <TextBlock Classes="cellNum" HorizontalAlignment="Left" Text="{Binding Index}" />
+                                            <TextBlock Grid.Column="1" Classes="cell" Text="{Binding Name}" />
+                                            <TextBlock Grid.Column="2" Classes="cell" FontFamily="{DynamicResource FontMono}" Text="{Binding Display}" />
+                                            <TextBlock Grid.Column="3" Classes="cellNum" Text="{Binding Line}" />
+                                            <TextBlock Grid.Column="4" Classes="cellNum" Text="{Binding Position}" />
+                                            <TextBlock Grid.Column="5" Classes="cellNum" Text="{Binding Length}" />
+                                            <TextBlock Grid.Column="6" Classes="cell" HorizontalAlignment="Center" Text="{Binding SuccessText}" />
+                                        </Grid>
+                                    </DataTemplate>
+                                </ListBox.ItemTemplate>
+                            </ListBox>
+
+                            <TextBlock Grid.Row="3" Text="{loc:Tr 'Capture'}" FontWeight="SemiBold" />
+                            <Grid Grid.Row="4" ColumnDefinitions="32,*,40,52,46">
+                                <TextBlock Classes="tableHeader" Text="#" />
+                                <TextBlock Grid.Column="1" Classes="tableHeader" Text="{loc:Tr 'Value'}" />
+                                <TextBlock Grid.Column="2" Classes="tableHeader" Text="{loc:Tr 'Line'}" HorizontalAlignment="Right" />
+                                <TextBlock Grid.Column="3" Classes="tableHeader" Text="{loc:Tr 'Index'}" HorizontalAlignment="Right" />
+                                <TextBlock Grid.Column="4" Classes="tableHeader" Text="{loc:Tr 'Length'}" HorizontalAlignment="Right" />
+                            </Grid>
+                            <ListBox Grid.Row="5" Name="CaptureList" Classes="ResultTable">
+                                <ListBox.ItemTemplate>
+                                    <DataTemplate x:DataType="models:RegexCaptureItem">
+                                        <Grid ColumnDefinitions="32,*,40,52,46">
+                                            <TextBlock Classes="cellNum" HorizontalAlignment="Left" Text="{Binding Index}" />
+                                            <TextBlock Grid.Column="1" Classes="cell" FontFamily="{DynamicResource FontMono}" Text="{Binding Display}" />
+                                            <TextBlock Grid.Column="2" Classes="cellNum" Text="{Binding Line}" />
+                                            <TextBlock Grid.Column="3" Classes="cellNum" Text="{Binding Position}" />
+                                            <TextBlock Grid.Column="4" Classes="cellNum" Text="{Binding Length}" />
+                                        </Grid>
+                                    </DataTemplate>
+                                </ListBox.ItemTemplate>
+                            </ListBox>
+                        </Grid>
+                    </Grid>
+
+                    <TextBlock Grid.Row="4" Name="StatusText" Classes="dim" Text="{loc:Tr 'Waiting'}" />
                 </Grid>
             </Border>
         </Grid>
Modified +228 -20
diff --git a/XCoder.App/Tools/Regex/RegexToolView.axaml.cs b/XCoder.App/Tools/Regex/RegexToolView.axaml.cs
index 090d08e..f523e26 100644
--- a/XCoder.App/Tools/Regex/RegexToolView.axaml.cs
+++ b/XCoder.App/Tools/Regex/RegexToolView.axaml.cs
@@ -1,16 +1,22 @@
 using System;
 using System.Collections.Generic;
-using System.Text;
+using System.Diagnostics;
 using System.Text.RegularExpressions;
+using System.Threading.Tasks;
 using Avalonia.Controls;
 using Avalonia.Interactivity;
+using NewLife.XCoder.Models;
 using NewLife.XCoder.Services;
+using RegexExpression = System.Text.RegularExpressions.Regex;
 
 namespace NewLife.XCoder.Tools.Regex;
 
 /// <summary>正则表达式工具</summary>
 public partial class RegexToolView : UserControl
 {
+    private RegexExpression? _regex;
+    private Boolean _running;
+
     /// <summary>实例化</summary>
     public RegexToolView()
     {
@@ -19,6 +25,10 @@ public partial class RegexToolView : UserControl
         MatchButton.Click += OnMatch;
         ReplaceButton.Click += OnReplace;
 
+        MatchList.SelectionChanged += OnMatchSelected;
+        GroupList.SelectionChanged += OnGroupSelected;
+        CaptureList.SelectionChanged += OnCaptureSelected;
+
         PatternBox.ContextMenu = CreateEditorMenu(PatternBox, "Pattern templates", RegexTemplateLibrary.PatternDirectory, true);
         InputBox.ContextMenu = CreateEditorMenu(InputBox, "Sample texts", RegexTemplateLibrary.SampleDirectory, false);
     }
@@ -37,46 +47,244 @@ public partial class RegexToolView : UserControl
         }
     }
 
-    private void OnMatch(Object? sender, RoutedEventArgs e)
+    #region 匹配与替换
+    private async void OnMatch(Object? sender, RoutedEventArgs e) => await RunMatchAsync();
+
+    private async void OnReplace(Object? sender, RoutedEventArgs e) => await RunReplaceAsync();
+
+    /// <summary>执行匹配,逐行刷新匹配、分组、捕获表格</summary>
+    /// <returns>匹配数量;表达式无效或超时返回 0</returns>
+    public async Task<Int32> RunMatchAsync()
     {
+        var pattern = PatternBox.Text ?? "";
+        var input = InputBox.Text ?? "";
+        if (!CanRun(pattern, input)) return 0;
+
+        _running = true;
         try
         {
-            var input = InputBox.Text ?? "";
-            var list = RegexService.Matches(input, PatternBox.Text ?? "", Options);
-            var sb = new StringBuilder();
-            for (var i = 0; i < list.Count; i++)
+            SetStatus("正在匹配...", false);
+
+            var options = Options;
+            var sw = Stopwatch.StartNew();
+            var result = await Task.Run(() =>
             {
-                var item = list[i];
-                sb.AppendLine($"#{i + 1}  L{LineOf(input, item.Index)}  [{item.Index},{item.Length}]  {item.Value}");
-                if (item.Groups.Count > 1)
-                {
-                    for (var g = 1; g < item.Groups.Count; g++) sb.AppendLine($"    ${g} = {item.Groups[g]}");
-                }
-            }
+                var regex = RegexService.Create(pattern, options);
+                return (Regex: regex, Items: BuildMatches(regex, input));
+            });
+            sw.Stop();
 
-            OutputBox.Text = sb.ToString().TrimEnd();
-            SetStatus($"共 {list.Count} 处匹配", false);
+            _regex = result.Regex;
+            SetMatches(result.Items);
+            OutputBox.Text = "";
+
+            SetStatus(LocalizationService.Format("Matched {0} occurrences in {1} ms", result.Items.Count, sw.ElapsedMilliseconds), false);
+            return result.Items.Count;
+        }
+        catch (RegexMatchTimeoutException)
+        {
+            SetMatches([]);
+            SetStatus("正则匹配超时!", true);
+            return 0;
         }
         catch (Exception ex)
         {
-            OutputBox.Text = "";
+            SetMatches([]);
             SetStatus(ex.Message, true);
+            return 0;
+        }
+        finally
+        {
+            _running = false;
         }
     }
 
-    private void OnReplace(Object? sender, RoutedEventArgs e)
+    /// <summary>执行替换,结果写入右侧结果框并刷新匹配表格</summary>
+    /// <returns>替换数量;表达式无效或超时返回 0</returns>
+    public async Task<Int32> RunReplaceAsync()
     {
+        var pattern = PatternBox.Text ?? "";
+        var input = InputBox.Text ?? "";
+        if (!CanRun(pattern, input)) return 0;
+
+        var replacement = ReplacementBox.Text ?? "";
+
+        _running = true;
         try
         {
-            OutputBox.Text = RegexService.Replace(InputBox.Text ?? "", PatternBox.Text ?? "", ReplacementBox.Text ?? "", Options);
-            SetStatus("替换完成", false);
+            SetStatus("正在替换...", false);
+
+            var options = Options;
+            var sw = Stopwatch.StartNew();
+            var result = await Task.Run(() =>
+            {
+                var regex = RegexService.Create(pattern, options);
+                var items = BuildMatches(regex, input);
+                return (Regex: regex, Items: items, Output: regex.Replace(input, replacement));
+            });
+            sw.Stop();
+
+            _regex = result.Regex;
+            SetMatches(result.Items);
+            OutputBox.Text = result.Output;
+
+            SetStatus(LocalizationService.Format("Replaced {0} occurrences in {1} ms", result.Items.Count, sw.ElapsedMilliseconds), false);
+            return result.Items.Count;
+        }
+        catch (RegexMatchTimeoutException)
+        {
+            SetMatches([]);
+            SetStatus("正则替换超时!", true);
+            return 0;
         }
         catch (Exception ex)
         {
-            OutputBox.Text = "";
+            SetMatches([]);
             SetStatus(ex.Message, true);
+            return 0;
+        }
+        finally
+        {
+            _running = false;
+        }
+    }
+
+    private Boolean CanRun(String pattern, String input)
+    {
+        if (_running) return false;
+
+        if (String.IsNullOrEmpty(pattern))
+        {
+            SetStatus("请输入正则表达式", true);
+            return false;
+        }
+        if (String.IsNullOrEmpty(input))
+        {
+            SetStatus("请输入内容", true);
+            return false;
+        }
+
+        return true;
+    }
+
+    private static List<RegexMatchItem> BuildMatches(RegexExpression regex, String input)
+    {
+        var items = new List<RegexMatchItem>();
+        var index = 1;
+        var line = 1;
+        var scanned = 0;
+        foreach (Match match in regex.Matches(input))
+        {
+            // 匹配按位置递增返回,一次扫描即可算出每项行号
+            while (scanned < match.Index && scanned < input.Length)
+            {
+                if (input[scanned] == '\n') line++;
+                scanned++;
+            }
+
+            items.Add(new RegexMatchItem
+            {
+                Index = index++,
+                Value = match.Value,
+                Line = line,
+                Position = match.Index,
+                Length = match.Length,
+                Match = match
+            });
+        }
+
+        return items;
+    }
+
+    private void SetMatches(IReadOnlyList<RegexMatchItem> items)
+    {
+        MatchList.ItemsSource = items;
+        GroupList.ItemsSource = null;
+        CaptureList.ItemsSource = null;
+    }
+    #endregion
+
+    #region 选中联动
+    private void OnMatchSelected(Object? sender, SelectionChangedEventArgs e)
+    {
+        GroupList.ItemsSource = null;
+        CaptureList.ItemsSource = null;
+
+        if (MatchList.SelectedItem is not RegexMatchItem item || item.Match == null) return;
+
+        SelectInInput(item.Position, item.Length);
+
+        var input = InputBox.Text ?? "";
+        var match = item.Match;
+        var groups = new List<RegexGroupItem>(match.Groups.Count);
+        for (var i = 0; i < match.Groups.Count; i++)
+        {
+            var group = match.Groups[i];
+            groups.Add(new RegexGroupItem
+            {
+                Index = i,
+                Name = _regex?.GroupNameFromNumber(i) ?? i.ToString(),
+                Value = group.Value,
+                Line = group.Success ? LineOf(input, group.Index) : 0,
+                Position = group.Index,
+                Length = group.Length,
+                Success = group.Success,
+                Group = group
+            });
         }
+
+        GroupList.ItemsSource = groups;
+        if (groups.Count > 0) GroupList.SelectedIndex = 0;
+    }
+
+    private void OnGroupSelected(Object? sender, SelectionChangedEventArgs e)
+    {
+        CaptureList.ItemsSource = null;
+
+        if (GroupList.SelectedItem is not RegexGroupItem item || item.Group == null) return;
+
+        if (item.Success) SelectInInput(item.Position, item.Length);
+
+        var input = InputBox.Text ?? "";
+        var group = item.Group;
+        var captures = new List<RegexCaptureItem>(group.Captures.Count);
+        for (var i = 0; i < group.Captures.Count; i++)
+        {
+            var capture = group.Captures[i];
+            captures.Add(new RegexCaptureItem
+            {
+                Index = i,
+                Value = capture.Value,
+                Line = LineOf(input, capture.Index),
+                Position = capture.Index,
+                Length = capture.Length,
+                Capture = capture
+            });
+        }
+
+        CaptureList.ItemsSource = captures;
+    }
+
+    private void OnCaptureSelected(Object? sender, SelectionChangedEventArgs e)
+    {
+        if (CaptureList.SelectedItem is RegexCaptureItem item) SelectInInput(item.Position, item.Length);
+    }
+
+    private void SelectInInput(Int32 position, Int32 length)
+    {
+        var text = InputBox.Text ?? "";
+        var start = Math.Clamp(position, 0, text.Length);
+        var end = Math.Clamp(start + Math.Max(length, 0), start, text.Length);
+
+        InputBox.CaretIndex = end;
+        InputBox.SelectionStart = start;
+        InputBox.SelectionEnd = end;
+
+        var line = LineOf(text, start);
+        var count = InputBox.GetLineCount();
+        if (count > 0) InputBox.ScrollToLine(Math.Clamp(line - 1, 0, count - 1));
     }
+    #endregion
 
     private ContextMenu CreateEditorMenu(TextBox box, String title, String directory, Boolean isPattern)
     {