从字符串只返回数字(0-9) [英] return only Digits 0-9 from a String
问题描述
我需要一个正规的前pression,我可以在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。
- 添加设置musicfreak的回答后使用RegexBuddy 产生code
的VBScript code
暗淡myRegExp,ResultString
设置myRegExp =新的RegExp
myRegExp.Global = TRUE
myRegExp.Pattern =[^ \\ D]
ResultString = myRegExp.Replace(SubjectString,)
VB.NET
昏暗ResultString作为字符串
尝试
昏暗RegexObj作为新的正则表达式([^ \\ D])
ResultString = RegexObj.Replace(SubjectString,)
抓住EX作为的ArgumentException
语法错误在正规前pression
结束Try
C#
字符串resultString = NULL;
尝试{
正则表达式regexObj =新的正则表达式(@[^ \\ D]);
resultString = regexObj.Replace(subjectString,);
}赶上(ArgumentException的前){
//语法错误在正规前pression
}
我不知道是否有VBScript的某种的正规前pression替换功能,但如果这样做,那么你可以做一些事情像这样的伪code:
reg_replace(/ \\ D + /克,'',your_string)
我不知道的VBScript,所以我不能给你确切的code,但这将消除任何不是一个数字。
编辑:确保有全局标志(以下简称G在正则表达式的结束),否则只会在字符串的第一个非数字匹配
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.
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.
I may have missed a similar regex but I did search on regexlib.com.
[EDIT] - Added code generated by RegexBuddy after setting up musicfreak's answer
VBScript Code
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
}
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)
I don't know VBScript so I can't give you the exact code but this would remove anything that is not a number.
EDIT: 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屋!