只返回字符串中的数字 0-9 [英] return only Digits 0-9 from a String
问题描述
我需要一个可以在 VBScript 和 .NET 中使用的正则表达式,它只返回在字符串中找到的数字.
I need a regular expression that I can use in VBScript and .NET that will return only the numbers that are found in a string.
例如,以下任何字符串"应仅返回 1231231234
For Example any of the following "strings" should return only 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
这将用于电子邮件解析器以查找客户可能在电子邮件中提供的电话号码并进行数据库搜索.
This will be used in an email parser to find telephone numbers that customers may provide in the email and do a database search.
我可能错过了类似的正则表达式,但我确实在 regexlib.com 上进行了搜索.
I may have missed a similar regex but I did search on regexlib.com.
- 添加由 RegexBuddy 在设置 musicfreak 的答案后生成的代码
- Added code generated by RegexBuddy after setting up musicfreak's answer
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
}
推荐答案
我不知道 VBScript 是否有某种正则表达式替换"功能,但如果有,那么您可以执行如下伪代码:
I don't know if VBScript has some kind of a "regular expression replace" function, but if it does, then you could do something like this pseudocode:
reg_replace(/D+/g, '', your_string)
我不知道 VBScript,所以我不能给你确切的代码,但这会删除任何不是数字的东西.
I don't know VBScript so I can't give you the exact code but this would remove anything that is not a number.
确保有全局标志(正则表达式末尾的g"),否则它只会匹配字符串中的第一个非数字.
Make sure to have the global flag (the "g" at the end of the regexp), otherwise it will only match the first non-number in your string.
这篇关于只返回字符串中的数字 0-9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!