83 lines
2.8 KiB
C#
83 lines
2.8 KiB
C#
using System.Collections.Generic;
|
||
|
||
namespace CustomOpenAddins
|
||
{
|
||
/// <summary>
|
||
/// 数字匹配工具类
|
||
/// </summary>
|
||
public static class NumberMatcher
|
||
{
|
||
/// <summary>
|
||
/// 匹配中文数字的正则表达式(零到九,包含大写)
|
||
/// </summary>
|
||
private const string ChineseNumberPattern = "[零一二三四五六七八九壹贰叁肆伍陆柒捌玖两]";
|
||
|
||
/// <summary>
|
||
/// 匹配希腊数字的正则表达式(Ⅰ到Ⅹ)
|
||
/// </summary>
|
||
private const string GreekNumberPattern = "[ⅠⅡⅢⅣⅤⅥⅦⅧⅨ]";
|
||
|
||
/// <summary>
|
||
/// 检查字符串是否是中文数字
|
||
/// </summary>
|
||
/// <param name="input">输入字符串</param>
|
||
/// <returns>是否匹配</returns>
|
||
public static bool IsChineseNumber(string input)
|
||
{
|
||
if (string.IsNullOrEmpty(input))
|
||
return false;
|
||
|
||
return System.Text.RegularExpressions.Regex.IsMatch(input, $"^{ChineseNumberPattern}$");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 检查字符串是否是希腊数字
|
||
/// </summary>
|
||
/// <param name="input">输入字符串</param>
|
||
/// <returns>是否匹配</returns>
|
||
public static bool IsGreekNumber(string input)
|
||
{
|
||
if (string.IsNullOrEmpty(input))
|
||
return false;
|
||
|
||
return System.Text.RegularExpressions.Regex.IsMatch(input, $"^{GreekNumberPattern}$");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从字符串中提取第一个匹配的数字(中文或希腊数字)
|
||
/// </summary>
|
||
/// <param name="input">输入字符串</param>
|
||
/// <returns>匹配到的数字字符串,未匹配返回null</returns>
|
||
public static string ExtractFirstNumber(string input)
|
||
{
|
||
if (string.IsNullOrEmpty(input))
|
||
return null;
|
||
|
||
var pattern = $"({ChineseNumberPattern}|{GreekNumberPattern})";
|
||
var match = System.Text.RegularExpressions.Regex.Match(input, pattern);
|
||
|
||
return match.Success ? match.Value : null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从字符串中提取所有匹配的数字(中文或希腊数字)
|
||
/// </summary>
|
||
/// <param name="input">输入字符串</param>
|
||
/// <returns>匹配到的数字字符串集合</returns>
|
||
public static IEnumerable<string> ExtractAllNumbers(string input)
|
||
{
|
||
if (string.IsNullOrEmpty(input))
|
||
yield break;
|
||
|
||
var pattern = $"({ChineseNumberPattern}|{GreekNumberPattern})";
|
||
var matches = System.Text.RegularExpressions.Regex.Matches(input, pattern);
|
||
|
||
foreach (System.Text.RegularExpressions.Match match in matches)
|
||
{
|
||
yield return match.Value;
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|