正则表达式替换所有字符,除了数字 [英] RegEx for replacing all characters apart from numbers

查看:636
本文介绍了正则表达式替换所有字符,除了数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串的数据在它的数字。这种模式是不相符的。我想从字符串且只有被定义为允许一个字符提取所有数字。我想正则表达式可能是这样做的最简单的方法。你能提供一个正则表达式图案可能做到这一点,因为我觉得正则表达式是巫术,只有正则表达式医药男人知道它是如何工作

例如:/

 Q1W2EE3R45T=12345
WWED456J=456
ABC123=123
N123=N123// N是允许的字符
 

更新:这是我的code:

  VAR数据= Value.Split(新的char [] {','},StringSplitOptions.RemoveEmptyEntries);
数据= data.Select(X => Regex.Replace(X,??????,的String.Empty))的ToArray()。
 

解决方案

 字符串numbersOnly = Regex.Replace(STR,@[^ \ D]的String.Empty);
 

使用 Regex.Replace(字符串,字符串,字符串) 的静态方法。

样品

要允许 N ,你可以换着花样给 [^ \ DN] 。如果你正在寻找 N ,以及你可以使用的 RegexOptions.IgnoreCase 或类改为 [^ \ DNN]

If I have a string of data with numbers in it. This pattern is not consistent. I would like to extract all numbers from the string and only a character that is defined as allowed. I thought RegEx might be the easiest way of doing this. Could you provide a regex patter that may do this as I think regex is voodoo and only regex medicine men know how it works

eg/

"Q1W2EE3R45T" = "12345"
"WWED456J" = "456"
"ABC123" = "123"
"N123" = "N123" //N is an allowed character

UPDATE: Here is my code:

var data = Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
data = data.Select(x => Regex.Replace(x, "??????", String.Empty)).ToArray();

解决方案

String numbersOnly = Regex.Replace(str, @"[^\d]", String.Empty);

Using Regex.Replace(string,string,string) static method.

Sample

To allow N you can change the pattern to [^\dN]. If you're looking for n as well you can either apply RegexOptions.IgnoreCase or change the class to [^\dnN]

这篇关于正则表达式替换所有字符,除了数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆