小编典典

从字符串仅返回数字0-9

c#

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

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

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

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

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

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

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
}

阅读 456

收藏
2020-05-19

共1个答案

小编典典

我不知道VBScript是否具有某种“正则表达式替换”功能,但是如果这样做,则可以执行以下伪代码操作:

reg_replace(/\D+/g, '', your_string)

我不知道VBScript,所以我不能给您确切的代码,但这会删除任何非数字的内容。

编辑:确保具有全局标志(在正则表达式末尾的“ g”),否则它将仅与字符串中的第一个非数字匹配。

2020-05-19