【问题标题】:return only Digits 0-9 from a String从字符串中仅返回数字 0-9
【发布时间】:2010-10-25 01:45:59
【问题描述】:

我需要一个可以在 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
}

【问题讨论】:

  • 正如我所说,\D 比 ^\d 简单。

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


【解决方案1】:

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

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

【讨论】:

  • ps。我知道我已经用 C# 回答了一个 VB 问题,但是因为它是 .NET,所以我认为值得将这个想法放在那里。对于这么简单的事情,RegEx 似乎有点矫枉过正。
  • 我实际上需要 VBScript 才能在经典 ASP 页面中使用,但感谢您的回答。
  • 我正要发表评论,“/Clearly/,正则表达式会更快”,但我在 Mono 中运行了一个(不科学的)基准测试,Linq 赢了(大约一半正则表达式所用的持续时间)。 :) 所以我的帽子给你了。
  • +10。给大家提个醒,别忘了using System.Linq;。对我来说,VS2010 只是说字符串没有“Where”这样的方法,并且 IntelliSense 不会给我自动添加 using 语句。
  • 您还需要使用 System.Linq.Expressions: using System.Linq;使用 System.Linq.Expressions;
【解决方案2】:

作为主要.Net 解决方案的替代方案,改编自similar question's 答案:

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

【讨论】:

    【解决方案3】:

    我不知道 VBScript 是否有某种“正则表达式替换”功能,但如果有,那么您可以执行以下伪代码:

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

    我不知道 VBScript,所以我不能给你确切的代码,但这会删除任何不是数字的东西。

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

    【讨论】:

    • 谢谢!这正是我想要做的。我知道它必须有点简单。我正在使用 RegExBuddy 并将尝试对其进行测试,然后发布 VBScript 代码。我相信 VBScript 会做一个替换。
    • 如果你想用 .NET 类来做,基本上是 re = Regex("\D");重新替换(“123 123 1234”,“”)。记得缓存你的 Regex 对象(不要在每次调用方法时都编译它们)。
    【解决方案4】:

    注意:这里你只解决了一半的问题。

    对于“在野外”输入的美国电话号码,您可能有:

    • 带或不带“1”前缀的电话号码
    • 带或不带区号的电话号码
    • 带有分机号码的电话号码(如果您盲目地删除所有非数字,您将错过“x”或“Ext.”或其他任何在线信息)。
    • 可能是用助记字母编码的数字(800-BUY-THIS 或其他)

    您需要在代码中添加一些智能,以使生成的数字列表符合您在数据库中实际搜索的单一标准。

    你可以做一些简单的事情来解决这个问题:

    • 在 RegEx 删除非数字之前,查看字符串中是否有“x”。如果有,把它后面的所有东西都砍掉(将处理大多数版本的写分机号码)。

    • 对于任何以“1”开头的 10 位以上数字,去掉 1。它不是区号的一部分,美国区号从 2xx 范围开始。

    • 对于任何仍然超过 10 位的数字,假设余数是某种扩展,并将其砍掉。

    • 使用“ends-with”模式搜索(SELECT * FROM mytable WHERE phonenumber LIKE 'blah%')进行数据库搜索。这将处理未提供区号的位置(尽管可能出错),但您的数据库中有区号的数字。

    【讨论】:

    • 真的。我确实在正则表达式之后添加了一些东西,如果它是 10 位数字,则返回整个字符串,或者如果它更长,则返回 right(string,10)。你最后的建议是一个很好的建议,我会补充一点。谢谢! +1
    • 好点!我在下面添加了我的提交来解决这个问题。
    【解决方案5】:

    从表面上看,你试图捕捉任何 10 位数的电话号码....

    为什么不首先对文本进行字符串替换以删除以下任何字符。

    <SPACE> , . ( ) - [ ] 
    

    然后,您可以对 10 位数字进行正则表达式搜索。

    \d{10}
    

    【讨论】:

    • 这是现有的,但我想让它匹配更广泛的输入字符串。
    【解决方案6】:

    你有没有通过 regexlib 上的phone nr category。似乎有不少人可以满足您的需要。

    【讨论】:

      【解决方案7】:

      就richardtallent 提出的观点而言,此代码将处理您在分机号码方面的大部分问题,并且美国国家/地区代码 (+1) 被前置。

      不是最优雅的解决方案,但我必须快速解决问题,以便继续我正在做的事情。

      我希望它对某人有所帮助。

       Public Shared Function JustNumbers(inputString As String) As String
              Dim outString As String = ""
              Dim nEnds As Integer = -1
      
              ' Cycle through and test the ASCII character code of each character in the string. Remove everything non-numeric except "x" (in the event an extension is in the string as follows):
              '    331-123-3451 extension 405  becomes 3311233451x405
              '    226-123-4567 ext 405        becomes 2261234567x405
              '    226-123-4567 x 405          becomes 2261234567x405
              For l = 1 To inputString.Length
                  Dim tmp As String = Mid(inputString, l, 1)
                  If (Asc(tmp) >= 48 And Asc(tmp) <= 57) Then
                      outString &= tmp
                  ElseIf Asc(tmp.ToLower) = 120
                      outString &= tmp
                      nEnds = l
                  End If
              Next
      
      
              ' Remove the leading US country code 1 after doing some validation
              If outString.Length > 0 Then
                  If Strings.Left(outString, 1) = "1" Then
      
                      ' If the nEnds flag is still -1, that means no extension was added above, set it to the full length of the string
                      ' otherwise, an extension number was detected, and that should be the nEnds (number ends) position.
                      If nEnds = -1 Then nEnds = outString.Length
      
                      ' We hit a 10+ digit phone number, this means an area code is prefixed; 
                      ' Remove the trailing 1 in case someone put in the US country code
                      ' This is technically safe, since there are no US area codes that start with a 1. The start digits are 2-9
                      If nEnds > 10 Then
                          outString = Right(outString, outString.Length - 1)
                      End If
                  End If
              End If
      
              Debug.Print(inputString + "          : became : " + outString)
      
              Return outString
          End Function
      

      【讨论】:

        【解决方案8】:

        最简单的解决方案,不用正则表达式:

        public string DigitsOnly(string s)
           {
             string res = "";
             for (int i = 0; i < s.Length; i++)
             {
               if (Char.IsDigit(s[i]))
                res += s[i];
             }
             return res;
           }
        

        【讨论】:

          猜你喜欢
          • 2019-09-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-30
          • 1970-01-01
          相关资源
          最近更新 更多