我有字母数字字符串列表。 例如:
1A
2B
7K
10A
我只想获取数字部分然后比较它们,如果它小于 10 我不需要将它添加到另一个列表中。 我想知道从字符串中拆分数字部分的正则表达式。 任何帮助。 到目前为止我所做的是:
if (x == y) // also handles null
return 0;
if (x == null)
return -1;
if (y == null)
return +1;
int ix = 0;
int iy = 0;
while (ix < x.Length && iy < y.Length)
{
if (Char.IsDigit(x[ix]) && Char.IsDigit(y[iy]))
{
// We found numbers, so grab both numbers
int ix1 = ix++;
int iy1 = iy++;
while (ix < x.Length && Char.IsDigit(x[ix]))
ix++;
while (iy < y.Length && Char.IsDigit(y[iy]))
iy++;
string numberFromX = x.Substring(ix1, ix - ix1);
string numberFromY = y.Substring(iy1, iy - iy1);
// Pad them with 0's to have the same length
int maxLength = Math.Max(
numberFromX.Length,
numberFromY.Length);
numberFromX = numberFromX.PadLeft(maxLength, '0');
numberFromY = numberFromY.PadLeft(maxLength, '0');
int comparison = _CultureInfo
.CompareInfo.Compare(numberFromX, numberFromY);
if (comparison != 0)
return comparison;
}
else
{
int comparison = _CultureInfo
.CompareInfo.Compare(x, ix, 1, y, iy, 1);
if (comparison != 0)
return comparison;
ix++;
iy++;
}
}
但我不想在我的方法中如此复杂。 所以我需要一个正则表达式来拆分。
最佳答案
试试char的IsDigit方法
var number = int.Parse(new string(someString.Where(char.IsDigit).ToArray()));
if(number<10)
{
someList.Add(number);
}
使用 All
和 IsDigit
你可以只获取字符串的数字部分,然后将其解析为 int 并进行比较:) 无需使用正则表达式
关于c# - 使用 C# 从字母数字字符串中拆分数字部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19288312/