using System;
using System.Collections.Generic;
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()
{
InitializeComponent();
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);
}
private RegexOptions Options
{
get
{
var options = RegexOptions.None;
if (IgnoreCaseBox.IsChecked == true) options |= RegexOptions.IgnoreCase;
if (MultilineBox.IsChecked == true) options |= RegexOptions.Multiline;
if (SinglelineBox.IsChecked == true) options |= RegexOptions.Singleline;
if (IgnorePatternWhitespaceBox.IsChecked == true) options |= RegexOptions.IgnorePatternWhitespace;
return options;
}
}
#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
{
SetStatus("正在匹配...", false);
var options = Options;
var sw = Stopwatch.StartNew();
var result = await Task.Run(() =>
{
var regex = RegexService.Create(pattern, options);
return (Regex: regex, Items: BuildMatches(regex, input));
});
sw.Stop();
_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)
{
SetMatches([]);
SetStatus(ex.Message, true);
return 0;
}
finally
{
_running = false;
}
}
/// <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
{
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)
{
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)
{
var menu = new ContextMenu();
void Rebuild()
{
var cut = new MenuItem { Header = LocalizationService.T("Cut") };
cut.Click += (_, _) => box.Cut();
var copy = new MenuItem { Header = LocalizationService.T("Copy") };
copy.Click += (_, _) => box.Copy();
var paste = new MenuItem { Header = LocalizationService.T("Paste") };
paste.Click += (_, _) => box.Paste();
var selectAll = new MenuItem { Header = LocalizationService.T("Select all") };
selectAll.Click += (_, _) => box.SelectAll();
var items = new List<Object> { cut, copy, paste, selectAll, new Separator() };
var templates = new MenuItem { Header = LocalizationService.T(title) };
FillTemplateItems(templates.Items, RegexTemplateLibrary.Load(directory), box, isPattern);
if (templates.ItemCount > 0) items.Add(templates);
menu.ItemsSource = items;
}
menu.Opening += (_, _) => Rebuild();
Rebuild();
return menu;
}
private void FillTemplateItems(ItemCollection items, IReadOnlyList<RegexTemplateNode> nodes, TextBox box, Boolean isPattern)
{
foreach (var node in nodes)
{
if (!node.IsFile)
{
var group = new MenuItem { Header = node.Name };
FillTemplateItems(group.Items, node.Children, box, isPattern);
items.Add(group);
continue;
}
var item = new MenuItem { Header = node.Name };
item.Click += (_, _) => InsertTemplate(box, node, isPattern);
items.Add(item);
}
}
private void InsertTemplate(TextBox box, RegexTemplateNode node, Boolean isPattern)
{
try
{
var content = RegexTemplateLibrary.Read(node);
var result = RegexTemplateLibrary.Insert(box.Text, box.SelectionStart, box.SelectionEnd, content);
box.Text = result.Text;
box.CaretIndex = result.Caret;
box.Focus();
var note = LocalizationService.T(isPattern ? "Pattern templates" : "Sample texts");
if (isPattern && IgnorePatternWhitespaceBox.IsChecked != true && RegexTemplateLibrary.NeedsIgnorePatternWhitespace(content))
{
IgnorePatternWhitespaceBox.IsChecked = true;
note += " · " + LocalizationService.T("Ignore whitespace");
}
SetStatus($"已套用模板:{node.FullName}({note})", false);
}
catch (Exception ex)
{
SetStatus(ex.Message, true);
}
}
private static Int32 LineOf(String text, Int32 index)
{
var line = 1;
var end = Math.Min(index, text.Length);
for (var i = 0; i < end; i++)
{
if (text[i] == '\n') line++;
}
return line;
}
private void SetStatus(String text, Boolean error)
{
StatusText.Text = NewLife.XCoder.Services.LocalizationService.Translate(text);
StatusText.Classes.Set("error", error);
StatusText.Classes.Set("ok", !error);
}
}
|