[英]Get non numeric values from string value c#
我有如下的价值
string value = "11,.Ad23";
int n;
bool isNumeric = int.TryParse(value, out n);
我控制字符串是否为数字。如果字符串不是数字并且具有非数字,我需要获取非数字值 ,如下所示
结果必须如下
,.Ad
我如何在C#中做到这一点?
如果非数字是连续的也没关系,那就很简单:
string nonNumericValue = string.Concat(value.Where(c => !Char.IsDigit(c)));
在线演示: http : //ideone.com/croMht
如果使用.NET 3.5。 正如评论中提到的, String.Concat
(或String.Join
答案中的String.Join )没有重载,它需要IEnumerable<string>
,因此您需要创建一个数组:
string nonNumericValue = string.Concat(value.Where(c => !Char.IsDigit(c)).ToArray());
这需要所有非数字。 如果您想取中间的部分,则跳过数字,然后取所有数字直到下一位:
string nonNumericValue = string.Concat(value.SkipWhile(Char.IsDigit)
.TakeWhile(c => !Char.IsDigit(c)));
正则表达式解决方案(将所有非数字值粘合在一起):
String source = "11,.Ad23";
String result = String.Join("", Regex
.Matches(source, @"\D{1}")
.OfType<Match>()
.Select(item => item.Value));
编辑:似乎您使用的是.Net的旧版本,在这种情况下,可以使用不带RegEx , Linq等的简单代码:
String source = "11,.Ad23";
StringBuilder sb = new StringBuilder(source.Length);
foreach (Char ch in source)
if (!Char.IsDigit(ch))
sb.Append(ch);
String result = sb.ToString();
尽管我喜欢提出的解决方案,但我认为更有效的方法是使用正则表达式,例如
[^\\D]
哪个叫
var regex = new Regex(@"[^\D]");
var nonNumeric = regex.Replace("11,.Ad23", ""));
哪个返回:
,.Ad
LINQ解决方案对您有用吗?
string value = "11,.Ad23";
var result = new string(value.Where(x => !char.IsDigit(x)).ToArray());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.