본문 바로가기
Regular Expressions(정규표현식)

SubMatches 컬렉션

2023. 8. 21.

이 글은 도움말을 번역한 글입니다.

SubMatches 컬렉션

정규식 부분 일치 문자열의 컬렉션입니다.

비고
SubMatches 컬렉션에는 개별 부분 일치 문자열이 포함되어 있으며 RegExp 개체의 Execute 메서드를 통해서만 만들 수 있습니다. SubMatches 컬렉션의 속성은 읽기 전용입니다.

정규식이 실행될 때 하위 식이 캡처 괄호로 묶여 있으면 0개 이상의 하위 일치가 발생할 수 있습니다. SubMatches 컬렉션의 각 항목은 정규식에서 찾아 캡처한 문자열입니다.

다음 코드는 정규식 검색에서 SubMatches 컬렉션을 가져오는 방법과 개별 멤버에 액세스하는 방법을 보여줍니다.

Function SubMatchTest(inpStr As String) As String
    Dim oRe As Object
    Dim oMatch As Object
    Dim oMatches As Object
    Dim retStr As String
    
    Set oRe = CreateObject("VBScript.RegExp")
    
    ' 이메일 주소를 찾습니다 (완벽한 정규식이 아닙니다).
    oRe.pattern = "(\w+)@(\w+)\.(\w+)"
    
    ' Matches 컬렉션을 가져옵니다.
    Set oMatches = oRe.Execute(inpStr)
    
    ' Matches 컬렉션의 첫 번째 항목을 가져옵니다.
    Set oMatch = oMatches(0)
    
    ' 결과 문자열을 생성합니다.
    ' Match 개체는 전체 일치하는 문자열을 의미합니다 - someone@example.com.
    retStr = "이메일 주소: " & oMatch.Value & vbCrLf
    
    ' 주소의 하위 일치 부분을 가져옵니다.
    retStr = retStr & "이메일 별칭: " & oMatch.SubMatches(0)
    retStr = retStr & vbCrLf
    
    retStr = retStr & "조직: " & oMatch.SubMatches(1)
    
    ' 결과 반환
    SubMatchTest = retStr
End Function

Sub TestSubMatch()
    MsgBox SubMatchTest("Please send mail to someone@example.com. Thanks!")
End Sub

' Output
' 이메일 주소: someone@ example.com
' 이메일 별칭: someone
' 조직: example

속성

Count Property

SubMatches Collection 내의 하위 문자열 개수를 반환합니다.읽기 전용 속성입니다.

다음 코드는 SubMatchesCollection에서 Count 속성을 사용하는 방법을 보여줍니다.

Function FindEmailAddresses(ByVal targetString As String) As Object
    Dim regEx As Object '정규표현식 객체 생성
    Dim matches As Object

    Set regEx = CreateObject("VBScript.RegExp")

    ' 이메일 주소를 찾습니다 (완벽한 정규식이 아닙니다).
    regEx.pattern = "(\w+)@(\w+)\.(\w+)"
    regEx.Global = True

    '특정 문자열에서 정규표현식에 일치하는 부분 찾기
    Set matches = regEx.Execute(targetString)

    ' 찾은 결과를 반환
    Set FindEmailAddresses = matches
End Function

Function GetSubMatchCount(matches As Object) As Long
    Dim oMatch As Object

    ' Matches 컬렉션의 첫 번째 항목을 가져옵니다.
    Set oMatch = matches(0)

    ' SubMatchesCollection 컬렉션의 개수 반환
    GetSubMatchCount = oMatch.SubMatches.count
End Function

Sub TestSubMatchCount()
    Dim inputStr As String
    Dim subMatchCount As Long
    Dim emailMatches As Object
    
    ' 입력 문자열 설정
    inputStr = "Please send mail to someone@example.com. Thanks!"
    
    ' 이메일 주소를 찾는 함수 호출
    Set emailMatches = FindEmailAddresses(inputStr)

    ' 첫 번째 Matches 개체의 SubMatchesCollection 컬렉션의 개수를 얻음
    subMatchCount = GetSubMatchCount(emailMatches)
    
    ' 결과 출력
    MsgBox "입력 문자열: " & inputStr & vbCrLf & "하위 일치 개체의 수: " & subMatchCount
End Sub

' Output
'입력 문자열: Please send mail to someone@example.com. Thanks!
'하위 일치 개체의 수: 3

Item Property

정규표현식에서 발견된 소괄호로 묶인 그룹에 일치하는 하위 문자열을 반환합니다. 읽기 전용 속성입니다.

비고

다음 코드는 SubMatchesCollection에서 Item 속성을 사용하는 방법을 보여줍니다.

Function FindPhoneNumbers(ByVal targetString As String) As Object
    Dim regEx As Object '정규표현식 객체 생성
    Dim matches As Object

    Set regEx = CreateObject("VBScript.RegExp") '생성

    '정규표현식 패턴 설정
    regEx.pattern = "\+([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)"
    regEx.Global = True

    '특정 문자열에서 정규표현식에 일치하는 부분 찾기
    Set matches = regEx.Execute(targetString)

    '찾은 결과를 반환
    Set FindPhoneNumbers = matches
End Function

Sub ExtractPhoneParts(matches As Object)
    Dim match As Object

    '찾은 결과를 순회
    For Each match In matches
        'SubMatches Collection에서 각 그룹을 추출하여 화면에 출력
        Debug.Print "전체 전화번호: " & match.Value
        Debug.Print "국가 코드: " & match.SubMatches.Item(0)
        Debug.Print "지역 코드: " & match.SubMatches.Item(1) & match.SubMatches.Item(2)
        Debug.Print "로컬 번호: " & match.SubMatches.Item(3)
    Next match
End Sub

Sub Main()
    Dim targetString As String
    Dim matches As Object

    '전화번호 예시 문자열
    targetString = "예시 전화번호: +82-02-1234-5678"

    '전화번호 찾기 함수 호출 및 전화번호의 구성 요소 추출 함수 호출
    Set matches = FindPhoneNumbers(targetString)
    ExtractPhoneParts matches
End Sub

' Output
' 전체 전화번호: +82-02-1234-5678
' 국가 코드: 82
' 지역 코드: 021234
' 로컬 번호: 5678

'Regular Expressions(정규표현식)' 카테고리의 다른 글

Matches 컬렉션  (0) 2023.08.21
Match 개체  (0) 2023.08.20
RegExp 개체  (0) 2023.08.20
정규 표현식 소개  (0) 2023.08.18