문자열에서 숫자 0-9 만 반환
문자열에있는 숫자 만 반환하는 VBScript 및 .NET에서 사용할 수있는 정규식이 필요합니다.
예를 들어 다음 "문자열"은 1231231234 만 반환해야합니다.
- 123123 1234
- (123) 123-1234
- 123-123-1234
- (123)123-1234
- 123.123.1234
- 123123 1234
- 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
씨#
string resultString = null;
try {
Regex regexObj = new Regex(@"[^\d]");
resultString = regexObj.Replace(subjectString, "");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
VBScript에 일종의 "정규식 바꾸기"기능이 있는지는 모르겠지만, 그렇다면 다음과 같은 의사 코드를 수행 할 수 있습니다.
reg_replace(/\D+/g, '', your_string)
나는 VBScript를 모르기 때문에 정확한 코드를 제공 할 수는 없지만 숫자가 아닌 것은 모두 제거합니다.
편집 : 전역 플래그 (정규식 끝에 "g")가 있는지 확인하십시오. 그렇지 않으면 문자열에서 첫 번째가 아닌 숫자와 만 일치합니다.
.NET에서는 문자열에서 숫자 만 추출 할 수 있습니다. 이렇게 :
string justNumbers = new String(text.Where(Char.IsDigit).ToArray());
주요 .Net
솔루션 의 대안으로 유사한 질문의 답변 에서 수정되었습니다 .
string justNumbers = string.Concat(text.Where(char.IsDigit));
참고 : 여기서 문제의 절반 만 해결했습니다.
"야생"으로 입력 된 미국 전화 번호의 경우 다음이있을 수 있습니다.
- "1"접두사가 있거나없는 전화 번호
- 지역 번호가 있거나없는 전화 번호
- 내선 번호가있는 전화 번호 (숫자가 아닌 모든 것을 맹목적으로 제거하면 "x"또는 "Ext."또는 회선에있는 모든 항목이 누락됩니다).
- 니모닉 문자로 인코딩 된 숫자 (800-BUY-THIS 등)
결과 숫자 목록을 데이터베이스에서 실제로 검색하는 단일 표준에 맞추려면 코드에 몇 가지 현명한 기능을 추가해야합니다.
이 문제를 해결하기 위해 수행 할 수있는 몇 가지 간단한 작업 :
정규식이 아닌 숫자를 제거하기 전에 문자열에 "x"가 있는지 확인하십시오. 있는 경우 모든 것을 잘라내십시오 (대부분의 내선 번호 작성 버전을 처리 함).
"1"로 시작하는 10 자리 이상의 숫자는 1을 잘라내십시오. 지역 번호의 일부가 아닙니다. 미국 지역 번호는 2xx 범위에서 시작합니다.
여전히 10 자리를 초과하는 숫자의 경우 나머지가 일종의 확장이라고 가정하고 잘라냅니다.
Do your database search using an "ends-with" pattern search (SELECT * FROM mytable WHERE phonenumber LIKE 'blah%'). This will handle sitations (although with the possibility of error) where the area code is not provided, but your database has the number with the area code.
By the looks of things, your trying to catch any 10 digit phone number....
Why not do a string replace first of all on the text to remove any of the following characters.
<SPACE> , . ( ) - [ ]
Then afterwards, you can just do a regex search for a 10 digit number.
\d{10}
Have you gone through the phone nr category on regexlib. Seems like quite a few do what you need.
In respect to the points made by richardtallent, this code will handle most of your issues in respect to extension numbers, and the US country code (+1) being prepended.
Not the most elegant solution, but I had to quickly solve the problem so I could move on with what I'm doing.
I hope it helps someone.
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
참고URL : https://stackoverflow.com/questions/844461/return-only-digits-0-9-from-a-string
'programing tip' 카테고리의 다른 글
존재하는 경우 PHP MYSQL UPDATE 또는 그렇지 않은 경우 INSERT? (0) | 2020.11.16 |
---|---|
플랫리스트를 다시 렌더링하는 방법은 무엇입니까? (0) | 2020.11.16 |
SQL 서버에서 지난달의 기록 가져 오기 (0) | 2020.11.16 |
javascript / jquery로 선행 0 제거 / 자르기 (0) | 2020.11.16 |
현장에서 중단 문제가 발생한 적이 언제입니까? (0) | 2020.11.16 |