using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using NewLife.XCoder.Tools.Regex;
namespace XCoder.App.Tests;
/// <summary>正则匹配与替换测试</summary>
public class RegexServiceTests
{
[Fact]
[DisplayName("匹配数量与位置正确")]
public void Matches_Positions()
{
var list = RegexService.Matches("a1 b22 c333", "\\d+");
Assert.Equal(3, list.Count);
Assert.Equal(1, list[0].Index);
Assert.Equal("22", list[1].Value);
Assert.Equal(8, list[2].Index);
}
[Fact]
[DisplayName("捕获组内容正确")]
public void Matches_Groups()
{
var list = RegexService.Matches("2026-11-11", "(\\d{4})-(\\d{2})-(\\d{2})");
Assert.Single(list);
Assert.Equal(4, list[0].Groups.Count);
Assert.Equal("2026", list[0].Groups[1]);
Assert.Equal("11", list[0].Groups[3]);
}
[Fact]
[DisplayName("替换支持分组引用")]
public void Replace_WithGroups()
{
var result = RegexService.Replace("2026-11-11", "(\\d{4})-(\\d{2})-(\\d{2})", "$3/$2/$1");
Assert.Equal("11/11/2026", result);
}
[Fact]
[DisplayName("忽略大小写选项生效")]
public void Matches_IgnoreCase()
{
var none = RegexService.Matches("Abc abc", "abc");
var ignore = RegexService.Matches("Abc abc", "abc", RegexOptions.IgnoreCase);
Assert.Single(none);
Assert.Equal(2, ignore.Count);
}
[Fact]
[DisplayName("非法表达式抛 ArgumentException 并带说明")]
public void Invalid_Pattern_Throws()
{
var ex = Assert.Throws<ArgumentException>(() => RegexService.Matches("abc", "("));
Assert.Contains("正则表达式无效", ex.Message);
}
}
|