使用 C# 从字母数字字符串中拆分数字部分

编程入门 行业动态 更新时间:2024-10-28 00:17:13
本文介绍了使用 C# 从字母数字字符串中拆分数字部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有字母数字字符串列表.例如:

I have alphanumeric string list. For example:

1A 2B 7K 10A

我只想获取数字部分然后比较它们,如果它小于 10,我不需要将它添加到另一个列表中.我想知道从字符串中拆分数字部分的正则表达式.任何帮助.到目前为止,我所做的是:

I want to get only the numeric part and then compare them, if it is less than 10 I need not to add it in another list. What I want to know the regex to split the numeric part from the string. Any help. What I have done till now is:

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++; } }

但我不想让我的方法如此复杂.所以我需要一个正则表达式来拆分.

But I don't want to be so complex in my approach. So I need a regex to split.

推荐答案

尝试字符的 IsDigit 方法

Try IsDigit method of char

var number = int.Parse(new string(someString.Where(char.IsDigit).ToArray())); if(number<10) { someList.Add(number); }

使用 All 和 IsDigit 您可以只取字符串的数字部分,然后将其解析为 int 并进行比较:) 无需使用正则表达式

using All and IsDigit you can take only numeric part of the string, then parse it to int and compare :) There is no need to use Regexes

更多推荐

使用 C# 从字母数字字符串中拆分数字部分

本文发布于:2023-11-06 04:35:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   字符串   字母

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!