이 글은 도움말을 번역한 글입니다.
RegExp 개체
RegExp개체는 간단한 정규 표현식 지원을 제공합니다.
VBA에서 정규 표현식을 사용하려면 RegExp 개체를 사용해야 합니다.
RegExp 개체 생성 방법
Early Binding을 사용하는 방법은 다음과 같습니다.
ALT+F11키를 누르고 VBE화면에서 도구> 참조에서 Microsoft VBSCript Regular Expressions 5.5를 참조합니다.
참조를 한 뒤에는 다음과 같이 선언하여 사용할 수 있습니다.
Dim regex As VBScript_RegExp_55.RegExp
Set regex = New VBScript_RegExp_55.RegExp
Late Binding은 다음과 같습니다.
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
속성
Global Property
패턴이 전체 검색 문자열의 모든 항목과 일치해야 하는지 아니면 첫 번째 항목만 일치해야 하는지를 나타내는 Boolean 값을 설정하거나 반환합니다.
Syntax
object.Global [= True | False ]
object : 항상 RegExp 개체입니다.
Global : Global 속성의 값은 검색이 전체 문자열에 적용되는 경우 True이고, 그렇지 않은 경우 False입니다. 기본값은 False입니다.
참고
다음 코드는 Global 속성의 사용법을 보여줍니다(Global 속성에 할당된 값을 변경하여 그 효과를 확인합니다)
Sub TestRegExp()
Dim pattern As String
Dim inputString As String
Dim result As String
' 입력할 패턴과 문자열 설정
pattern = "\d+" ' 숫자 패턴
inputString = "123 apples, 456 oranges, 789 bananas"
' 정규 표현식 함수 호출
result = RegExpTest(pattern, inputString)
' 결과 출력
Debug.Print result
End Sub
Function RegExpTest(ByVal patrn As String, ByVal strng As String) As String
Dim regEx As Object
Dim Match As Object
Dim Matches As Object
Dim s As String
' 정규 표현식 개체 생성
Set regEx = CreateObject("VBScript.RegExp")
regEx.pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
' 검색 수행
Set Matches = regEx.Execute(strng)
' Matches 컬렉션 반복
s = ""
For Each Match In Matches
s = s & "일치 위치: " & Match.FirstIndex & ". "
s = s & "일치 값: '" & Match.Value & "'."
s = s & vbCrLf
Next
' 결과 반환
RegExpTest = s
End Function
' Output
' 일치 위치: 0. 일치 값: '123'.
' 일치 위치: 12. 일치 값: '456'.
' 일치 위치: 25. 일치 값: '789'.
IgnoreCase Property
패턴 검색이 대소문자를 구분하는지 여부를 나타내는 부울 값을 설정하거나 반환합니다.
Syntax
object.IgnoreCase [= True | False ]
object : 항상 RegExp 개체입니다.
IgnoreCase : 검색이 대/소문자를 구분하는 경우 IgnoreCase 속성의 값은 False이고, 그렇지 않은 경우 True입니다. 기본값은 False입니다.
참고
다음 코드는 IgnoreCase 프로퍼티의 사용법을 보여줍니다. (IgnoreCase 속성에 할당된 값을 변경하여 그 효과를 확인합니다)
' 특정 단어 찾기 함수 정의
Function FindWord(ByVal inputText As String, ByVal searchWord As String, ByVal caseSensitive As Boolean) As Collection
Dim regExp As Object
Dim matches As Object
Dim match As Object
Dim result As New Collection
' RegExp 개체 생성
Set regExp = CreateObject("VBScript.RegExp")
' 정규 표현식 설정
regExp.pattern = "\b" & searchWord & "\b"
regExp.IgnoreCase = caseSensitive
regExp.Global = True
' 정규 표현식 적용
Set matches = regExp.Execute(inputText)
' 결과 추가
For Each match In matches
result.Add match.Value
Next match
' 결과 반환
Set FindWord = result
End Function
' 테스트 하기
Sub TestFindWord()
Dim words As Collection
Dim word As Variant
Dim inputText As String
inputText = "Apple tree in the garden, eating an apple."
Set words = FindWord(inputText, "apple", True) ' caseSensitive를 True로 설정
' 결과 출력
For Each word In words
Debug.Print word
Next word
End Sub
' Output
' Apple
' apple
Multiline Property
여러 줄에 걸친 텍스트에서 패턴 검색을 수행할지 여부를 나타내는 부울 값을 설정하거나 반환합니다.
Syntax
object.Multiline [= True | False]
object : object 인수는 항상 RegExp 개체의 이름입니다.
Multiline : 여러 줄에 걸친 텍스트에서 패턴을 검색하려면 True를 사용하고, 한 줄에서만 패턴을 검색하려면 False를 사용합니다. Multiline 속성의 기본값은 False입니다.
다음 코드는 Multiline 속성을 사용하는 방법을 보여줍니다.
' 모듈화된 함수
Function GetMultilineMatches(text As String, pattern As String) As Collection
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
' 패턴 설정
regex.pattern = pattern
regex.Global = True
regex.MultiLine = True ' Multiline 속성 활성화
' 패턴 일치 여부 확인
Dim matches As Object
Set matches = regex.Execute(text)
' 결과를 반환용 컬렉션에 추가
Dim match As Variant
Dim result As Collection
Set result = New Collection
For Each match In matches
result.Add match.Value
Next match
' 결과 반환
Set GetMultilineMatches = result
End Function
Sub MultilineExample()
' 여러 줄에 걸친 텍스트
Dim text As String
text = "Line 1: Hello" & vbCrLf & _
"Line 2: World" & vbCrLf & _
"Line 3: How are you?"
' 패턴 설정
Dim pattern As String
pattern = "^Line \d+:"
' GetMultilineMatches 함수를 사용하여 일치하는 결과 얻기
Dim matches As Collection
Set matches = GetMultilineMatches(text, pattern)
' 찾은 패턴 출력
Dim i As Integer
For i = 1 To matches.Count
Debug.Print matches.Item(i)
Next i
End Sub
Pattern Property
검색 중인 정규식 패턴을 설정하거나 반환합니다.
Syntax
object.Pattern [= "searchstring"]
object : 필수적인 요소. 항상 RegExp 개체의 이름입니다.
searchstring : 선택적인 요소. 검색할 정규 문자식입니다. 아래 설정 부분의 표에 정의된 정규식 문자를 포함합니다.
설정
특수 문자 및 시퀀스는 정규 표현식의 패턴 작성에 사용됩니다. 다음 표는 사용할 수 있는 문자 및 시퀀스의 예를 설명하고 제공합니다.
다음 코드는 Pattern 속성의 사용 방법을 보여줍니다.
Function FindPatternMatches(ByVal text As String, ByVal pattern As String) As Collection
' VBScript의 RegExp 개체 생성
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
' 패턴 설정
regex.pattern = pattern
regex.Global = True
' 텍스트에서 일치하는 항목 찾기
Dim matches As Object
Set matches = regex.Execute(text)
' 결과를 컬렉션에 추가하여 반환
Dim match As Variant
Dim result As Collection
Set result = New Collection
For Each match In matches
result.Add match.Value
Next match
Set FindPatternMatches = result
End Function
Sub ExampleUsage()
' 테스트용 텍스트
Dim text As String
text = "apple, banana, cherry, 123, orange"
' 패턴 설정 (단어로만 구성된 문자열 찾기)
Dim pattern As String
pattern = "\b[a-zA-Z]+\b"
' FindPatternMatches 함수 사용하여 일치하는 결과 얻기
Dim matches As Collection
Set matches = FindPatternMatches(text, pattern)
' 찾은 패턴 출력
Dim i As Integer
For i = 1 To matches.Count
Debug.Print matches.Item(i)
Next i
End Sub
' Output
' apple
' banana
' cherry
' orange
메서드
Execute Method
지정된 문자열에 대해 정규식 검색을 실행합니다.
Syntax
object.Execute(string)
object : 필수입니다. 항상 RegExp 개체의 이름입니다.
string : 필수입니다. 정규식이 실행되는 텍스트 문자열입니다.
참고
정규식 검색에 대한 실제 패턴은 RegExp 개체의 Pattern 속성을 이용하여 설정합니다.
Execute 메서드 string에서 일치되는 패턴이 있으면 Match 개체를 포함하는 Matches 컬렉션을 반환합니다. 일치되는 패턴이 없으면 Execute는 빈 Matches 컬렉션을 반환합니다.
아래 코드는 Execute 메서드의 사용법을 보여줍니다.
Function FindMatchesUsingRegExp(inputText As String, pattern As String) As Collection
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
' 패턴 설정
regex.pattern = pattern
regex.Global = True ' 모든 일치 항목 찾기
' 정규식 검색 수행
Dim matches As Object
Set matches = regex.Execute(inputText)
' 결과를 컬렉션에 저장하여 반환
Dim result As Collection
Set result = New Collection
Dim match As Variant
For Each match In matches
result.Add match.Value
Next match
Set FindMatchesUsingRegExp = result
End Function
Sub RegExpExecuteExample()
Dim inputText As String
inputText = "Today is 2023-08-20."
Dim pattern As String
pattern = "\d+" ' 숫자를 추출하는 정규식 패턴
' 정규식 검색을 위한 함수 호출
Dim matches As Collection
Set matches = FindMatchesUsingRegExp(inputText, pattern)
' 찾은 숫자 출력
Dim i As Integer
For i = 1 To matches.Count
MsgBox "Found: " & matches.Item(i)
Next i
End Sub
' Output
' Found: 2023
' Found: 08
' Found: 20
Replace Method
정규식 검색으로 찾은 텍스트를 대체합니다.
Syntax
object.Replace(string1, string2)
object : 필수적인 요소. 항상 RegExp 개체의 이름입니다.
string 1 : 필수적인 요소. String1은 텍스트 대체가 발생할 텍스트 문자열입니다.
string 2 : 필수 요소. String2는 대체될 텍스트 문자열입니다.
비고
대체되는 텍스트의 실제 패턴은 RegExp 개체의 Pattern 속성을 사용하여 설정됩니다.
Replace 메서드는 RegExp.Pattern의 텍스트를 string2로 대체하여 string1의 복사본을 반환합니다. 일치하는 항목을 찾지 못하는 경우, string1의 복사본이 변경되지 않은 채로 반환됩니다.
다음 코드는 Replace 메서드의 사용법을 설명합니다.
Function ReplaceTest(patrn As String, replStr As String) As String
Dim regEx As Object
Dim str1 As String
str1 = "The quick brown fox jumps over the lazy dog."
Set regEx = CreateObject("VBScript.RegExp")
regEx.pattern = patrn
regEx.IgnoreCase = True
ReplaceTest = regEx.Replace(str1, replStr)
End Function
Sub TestReplaceTest()
Dim result As String
result = ReplaceTest("fox", "cat")
MsgBox result
End Sub
' Output
' The quick brown cat jumps over the lazy dog.
또한 Replace 메서드는 패턴의 하위 표현식을 바꿀 수 있습니다. 이전 예제에 표시된 함수에 대한 다음 호출은 원래 문자열의 첫 번째 단어 쌍을 바꿉니다
ReplaceTest("(\S+)(\s+)(\S+)", "$3$2$1")
이전 예제에 적용하면 다음과 같습니다.
Function ReplaceTest(patrn As String, replStr As String) As String
Dim regEx As Object
Dim str1 As String
str1 = "The quick brown fox jumps over the lazy dog."
Set regEx = CreateObject("VBScript.RegExp")
regEx.pattern = patrn
regEx.IgnoreCase = True
ReplaceTest = regEx.Replace(str1, replStr)
End Function
Sub TestReplaceTest()
Dim result As String
result = ReplaceTest("(\S+)(\s+)(\S+)", "$3$2$1")
Debug.Print result
End Sub
' Output
' quick The brown fox jumps over the lazy dog.
Test Method
지정된 문자열에 대해 정규식 검색을 실행하고 패턴 일치 여부를 나타내는 부울 값을 반환합니다.
Syntax
object.Test(string)
object : 필수입니다. 항상 RegExp 객체의 이름입니다.
string : 필수입니다. 정규식이 실행되는 텍스트 문자열입니다.
비고
정규식 검색의 실제 패턴은 RegExp 개체의 Pattern 속성을 사용하여 설정됩니다. RegExp.Global 속성은 Test 메서드에 영향을 주지 않습니다.
Test 메서드는 일치하는 패턴이 발견되면 True를 반환하고 일치하는 패턴이 발견되지 않으면 False를 반환합니다.
다음 코드는 Test 메서드의 사용법을 보여줍니다.
Function RegExpTest(patrn As String, strng As String) As String
Dim regEx As Object
Dim retVal As Boolean
' Create regular expression.
Set regEx = CreateObject("VBScript.RegExp")
regEx.pattern = patrn
regEx.IgnoreCase = False
' Do the search test.
retVal = regEx.test(strng)
If retVal Then
RegExpTest = "하나 이상의 일치 항목이 발견되었습니다."
Else
RegExpTest = "일치하는 항목이 없습니다."
End If
End Function
Sub TestRegExpTest()
Dim result As String
result = RegExpTest("is.", "IS1 is2 IS3 is4")
MsgBox result
End Sub
' Output
' 하나 이상의 일치 항목이 발견되었습니다.
도움말 출처
Regular Expression (RegExp) Object
Table of contents Regular Expression (RegExp) Object Article 07/17/2015 In this article --> Provides simple regular expression support. For more information, see Introduction to Regular Expressions (Scripting). The following code illustrates the use of the
learn.microsoft.com
'Regular Expressions(정규표현식)' 카테고리의 다른 글
SubMatches 컬렉션 (0) | 2023.08.21 |
---|---|
Matches 컬렉션 (0) | 2023.08.21 |
Match 개체 (0) | 2023.08.20 |
정규 표현식 소개 (0) | 2023.08.18 |