c# - 仅返回字符串中的数字 0-9

标签 c# vb.net regex vbscript code-generation

我需要一个可以在 VBScript 和 .NET 中使用的正则表达式,它只返回在字符串中找到的数字。

例如,以下任何“字符串”都应仅返回 1231231234

  • 123 123 1234
  • (123) 123-1234
  • 123-123-1234
  • (123)123-1234
  • 123.123.1234
  • 123 123 1234
  • 1 2 3 1 2 3 1 2 3 4

这将在电子邮件解析器中用于查找客户可能在电子邮件中提供的电话号码并进行数据库搜索。

我可能错过了类似的正则表达式,但我确实在 regexlib.com 上进行了搜索。

[编辑] - 添加了 RegexBuddy 生成的代码设置 musicfreak 的答案后

VBScript 代码

Dim myRegExp, ResultString
Set myRegExp = New RegExp
myRegExp.Global = True
myRegExp.Pattern = "[^\d]"
ResultString = myRegExp.Replace(SubjectString, "")

VB.NET

Dim ResultString As String
Try
      Dim RegexObj As New Regex("[^\d]")
      ResultString = RegexObj.Replace(SubjectString, "")
Catch ex As ArgumentException
      'Syntax error in the regular expression
End Try

C#

string resultString = null;
try {
    Regex regexObj = new Regex(@"[^\d]");
    resultString = regexObj.Replace(subjectString, "");
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

最佳答案

在 .NET 中,您可以只从字符串中提取数字。像这样使用 Linq:

string justNumbers = new String(text.Where(Char.IsDigit).ToArray());

不要忘记包含 using System.Linq

关于c# - 仅返回字符串中的数字 0-9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/844461/

相关文章:

vb.net - 在 vb.net 中显示当前日期

php - 使用或不使用协议(protocol)验证 URL

regex - sed 中的特殊字符

c# - 防止在 MySQL 数据库中插入相同的值

c# - NLog - 如何解密日志文件

c# - TextBox 上的 Focus() 不起作用

c# - 数字线压缩和对接控件

xml - 将 XML 字符串反序列化为对象 VB.NET

c# - 带有事件处理程序的 VB.NET 到 C#

regex - 拆分驼峰列名称