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