从字符串中返回只有数字0至9的数字

16 浏览
0 Comments

从字符串中返回只有数字0至9的数字

我需要一个正则表达式,可以在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上搜索过了。

[EDIT] - 添加了由RegexBuddy生成的代码,after设置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
}

admin 更改状态以发布 2023年5月22日
0
0 Comments

作为主要的.Net解决方案的替代方案,改编自一个类似问题的回答:

string justNumbers = string.Concat(text.Where(char.IsDigit));

0
0 Comments

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

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

不要忘记包含using System.Linq

0