C# 是否有一种快捷方式来获取字符串中的左右运算符
C# Is there a short cut way to get Left and Right Operators in string
我有一个 string
,里面有 2 个 operators:"2 ≤ 8 > 25"
.
有什么办法可以在数组中分别得到左≤
运算符和右>
运算符如下?
res[0] = ≤
res[1] = >
请注意运算符(2
、8
、25
)旁边的数字 不是常量.
谢谢
如果您的输入始终采用您提供的格式,则正则表达式应该适用于此用例。
var input = "2 ≤ 8 > 25";
var pattern = new Regex("([^0-9 .]+)");
var result = pattern.Matches(input);
result[0]; // "≤"
result[1]; // ">"
注意:无论有没有spaces和小数位[=20,这都适用=].
正如 MikeT 在下面提到的,这段代码忽略了所有数字、space 或小数位,并且 return 只是运算符。
我建议查询 Unicode 类别:我们想要的只是 数学符号,可以通过简单的 获得Linq:
using System.Linq;
...
string formula = "2 ≤ 8 > 25";
// {'≤', '>'}
char[] res = formula
.Where(c => char.GetUnicodeCategory(c) == UnicodeCategory.MathSymbol)
.ToArray();
一起来看看:
Console.WriteLine(string.Join(Environment.NewLine,
res.Select((value, index) => $"res[{index}] = {value}")));
结果:
res[0] = ≤
res[1] = >
编辑: 相同的想法(Unicode 类别)实现为 正则表达式:
using System.Linq;
using System.Text.RegularExpressions;
...
string[] res = Regex
.Matches(formula, @"\p{Sm}") \ \p - Unicode Categoty; Sm - Symbol math
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
我有一个 string
,里面有 2 个 operators:"2 ≤ 8 > 25"
.
有什么办法可以在数组中分别得到左≤
运算符和右>
运算符如下?
res[0] = ≤
res[1] = >
请注意运算符(2
、8
、25
)旁边的数字 不是常量.
谢谢
如果您的输入始终采用您提供的格式,则正则表达式应该适用于此用例。
var input = "2 ≤ 8 > 25";
var pattern = new Regex("([^0-9 .]+)");
var result = pattern.Matches(input);
result[0]; // "≤"
result[1]; // ">"
注意:无论有没有spaces和小数位[=20,这都适用=].
正如 MikeT 在下面提到的,这段代码忽略了所有数字、space 或小数位,并且 return 只是运算符。
我建议查询 Unicode 类别:我们想要的只是 数学符号,可以通过简单的 获得Linq:
using System.Linq;
...
string formula = "2 ≤ 8 > 25";
// {'≤', '>'}
char[] res = formula
.Where(c => char.GetUnicodeCategory(c) == UnicodeCategory.MathSymbol)
.ToArray();
一起来看看:
Console.WriteLine(string.Join(Environment.NewLine,
res.Select((value, index) => $"res[{index}] = {value}")));
结果:
res[0] = ≤
res[1] = >
编辑: 相同的想法(Unicode 类别)实现为 正则表达式:
using System.Linq;
using System.Text.RegularExpressions;
...
string[] res = Regex
.Matches(formula, @"\p{Sm}") \ \p - Unicode Categoty; Sm - Symbol math
.Cast<Match>()
.Select(m => m.Value)
.ToArray();