0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ExcelVBA  正規表現を使用する

Last updated at Posted at 2022-09-03

自分用のメモなので、形は整ってないです。

Like演算子を利用した、擬似正規表現

' 「?」 任意の1文字          Like "AB?" は、「ABC」「AB0」などがヒット
' 「*」 0個以上の任意の文字  Like "AB*" は、「ABC」「ABCD」「AB」などがヒット
' 「#」 1文字の数字          Like "A##" は、「A56」「A89」などがヒット
' [A-Z]  []内の範囲のいずれか1文字  Like [B-F] は、B,C,D,E,F がヒットする
' [!A-Z]  []内の範囲に含まれない1文字  Like [!C-F] は、B,G,K,Z などがヒットする

Range("A1").Value = "ABCDE"
If Range("A1").Value Like "*C*" Then
    MsgBox "該当します"
Else
    MsgBox "該当しません"
End If


Range("A1").Value = "2017/1/6"
If Month(Range("A1").Value) Like "[0-5]" Then   ' 日付の月を取得
    MsgBox "該当します"
Else
    MsgBox "該当しません"
End If


Range("A1").Value = "コバヤシ"
If Left(Range("A1").Value, 1) Like "[サ-ソ]" Then  ' 値の1文字目がサ行であるか
    MsgBox "該当します"
Else
    MsgBox "該当しません"
End If

正規表現を利用する

' 正規表現は様々なバリエーションがあるので、詳しくはリンク先参照で

Dim reg As Variant
Dim str1 As String
Dim str2 As String

Set reg = CreateObject("VBScript.RegExp")  ' 正規表現オブジェクト 実行時バイディング
'Set reg = New regExp  '事前バインディング  参照設定で、Microsoft VBScript Regular Expression *.* にチェック

str1 = "ABCDE"
With reg
  .Global = True          ' 文字列全体を検索
  .IgnoreCase = False     ' 大文字小文字を区別する
  .pattern = "[A-Z]{5}"   ' 正規表現パターン。この場合は「A~Zのいずれかが5文字」という意味

  If .Test(str1) Then
  ' Range("A1").Valueが正規表現パターンにマッチした場合
    Debug.Print "マッチします"
  Else
    Debug.Print "マッチしません"
  End If
  
  .pattern = "[a-z]{5}"
  If .Test(str1) Then
    Debug.Print "マッチします"
  Else
    Debug.Print "マッチしません"
  End If
End With


'正規表現で検索し、文字列置換する
str1 = "aA12あbBカcCdzZ"
str2 = "0"
With reg
  .Global = True
  .IgnoreCase = False
  .pattern = "[A-Z]"
  Debug.Print .Replace(str1, str2)  'a012あb0カc0dz0
  'Replacedeで、str1内で正規表現にマッチした部分を、str2で置換する
End With

Debug.Print "------------------------"


'正規表現にマッチしたオブジェクトのCollectionを取得する
Dim mc As MatchCollection
'MatchオブジェクトのCollection  参照設定で、Microsoft VBScript Regular Expression *.* にチェックが必要みたい
Dim m As Match              '正規表現にマッチしたオブジェクト
Dim i As Long

With reg
  .Global = True
  .IgnoreCase = False
  .pattern = "[a-z]{2,4}"  '小文字英字の、2~4文字
  str1 = "a0bb0ccc0dddd0EEEE0"
  Set mc = .Execute(str1)  '正規表現でマッチした部分を、MatchオブジェクトとしてCollectionに格納する
  For Each m In mc
    Debug.Print m.Value   ' bb ccc dddd
  Next m
  
  Debug.Print "------------------------"
  
  '個別のサブマッチ文字列を取得。よくわからないが
  .pattern = "([a-z])([0-9])"  '小文字英字もしくは半角数字
  str1 = "a1b2c3d4e5"
  Set mc = .Execute(str1)
  For Each m In mc
    Debug.Print m.Value  ' a1 b2 c3 d4 e5 と順次出力
    For i = 0 To m.SubMatches.Count - 1
      Debug.Print m.SubMatches(i)  ' a 1 b 2 c 3 d 4 e 5 と、個別に出力される
    Next
    Debug.Print "---"
  Next
End With

Set reg = Nothing   'これはしておいたほうがいい

正規表現で、文字列を数値として扱うかを判定する  「100」「-12.350」は数値、「0001」「a1000」「1000」は数値としない判定になる

'文字列を数値と解釈するかを判定。数値であればTrueをリターン
Function func1(ByVal str1 As String) As Boolean

Dim Reg As Object
Set Reg = CreateObject("VBScript.RegExp")

If IsNumeric(str1) = False Then  '数値に評価できるかを判定
  func1 = False
  Exit Function
End If

Reg.Global = True
Reg.IgnoreCase = False
Reg.Pattern = "^[1-9]|^-[1-9]|^(0\.)|^(-0\.)"
' 半角数字の1~9で始まるか、0で始まるものは「0.」「-0.」だけを数値と判断する

If Reg.Test(str1) = False Then
  func1 = False
  Exit Function
End If

Reg.Pattern = "^[\d\.-]+$"
' 半角数字、「-」「.」だけで構成されるものを数値と判断する
If Reg.Test(str1) = False Then
  func1 = False
  Exit Function
End If

func1 = True   'ここまで来れば、数値とする

Set Reg = Nothing

End Function


Sub hhh()

'以下の結果はTrue
Debug.Print func1("100")
Debug.Print func1("-100")
Debug.Print func1("1.235")
Debug.Print func1("-1.235")
Debug.Print func1("0.123")
Debug.Print func1("-0.123")
Debug.Print func1("0.00258")
Debug.Print func1("-0.00258")
Debug.Print func1("12.3450")
Debug.Print func1("-12.3450")
Debug.Print func1("12.3450")
Debug.Print func1("-12.3450")
Debug.Print func1("12.345000")
Debug.Print func1("-12.345000")
Debug.Print func1("123456789012345")
Debug.Print func1("1234567890123456")
Debug.Print func1("1234567890123456789")
Debug.Print "------------------------------------"

'以下の結果はFalse
Debug.Print func1("0001")
Debug.Print func1("0010")
Debug.Print func1("0100")
Debug.Print func1("-0001")
Debug.Print func1("-0010")
Debug.Print func1("-0100")
Debug.Print func1("a1000")
Debug.Print func1("-a1000")
Debug.Print func1("\1000")
Debug.Print func1("-\1000")
Debug.Print func1("100")
Debug.Print func1("-100")
Debug.Print func1("12.345")
Debug.Print func1("-12.345")
Debug.Print func1("12,456,789")
Debug.Print func1("-12,456,789")
Debug.Print func1("25-55-68")
Debug.Print func1("26/45/48")
Debug.Print func1("5/10")
Debug.Print func1("-5/100")

End Sub

正規表現でエスケープが必要な文字をエスケープする  []{}|\ 等

Function EscapeSpecialCharactert(str1 As String) As String
'正規表現でエスケープが必要な文字をエスケープする

  str1 = Replace$(str1, "\", "\\")
  str1 = Replace$(str1, "?", "\?")
  str1 = Replace$(str1, "*", "\*")
  str1 = Replace$(str1, "+", "\+")
  str1 = Replace$(str1, ".", "\.")
  str1 = Replace$(str1, "|", "\|")
  str1 = Replace$(str1, "{", "\{")
  str1 = Replace$(str1, "}", "\}")
  str1 = Replace$(str1, "[", "\[")
  str1 = Replace$(str1, "]", "\]")
  str1 = Replace$(str1, "(", "\(")
  str1 = Replace$(str1, ")", "\)")
'  str1 = Replace$(str1, Chr(34), Chr(34) & Chr(34))
  'これは " を "" に変換するが、正規表現文字列を""で囲む場合には必要
  
  EscapeSpecialCharactert = str1

End Function
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?