VBA
Sub 正規表現で赤くする()
Dim c As Range
Dim reg As Object
Dim matches As Object
Dim m As Object
Set reg = CreateObject("VBScript.RegExp")
'対象パターン
reg.Pattern = "(new|stay|update)\(-?\d+(\.\d+)?\)"
reg.Global = True
reg.IgnoreCase = True
For Each c In Selection
If Not IsError(c.Value) Then
Set matches = reg.Execute(CStr(c.Value))
For Each m In matches
c.Characters( _
Start:=m.FirstIndex + 1, _
Length:=m.Length _
).Font.Color = vbRed
Next m
End If
Next c
End Sub
今回の正規表現
(new|update)(-?\d+(.\d+)?)
を分解すると、意外と単純です。
| 部分 | 意味 | マッチ例 |
|---|---|---|
(new|stay|update) |
new / stay / update のどれか | new |
\( |
( そのもの |
( |
-? |
- が「あってもなくてもよい」 |
- |
\d+ |
数字が1文字以上 |
2、26
|
(\.\d+)? |
小数部分が「あってもなくてもよい」 | .6 |
\) |
) そのもの |
) |
特に覚えておくと便利な記号
今回なら、まずこの5つを覚えるだけでかなり使えます。
- | → または。new|stay なら new または stay
- ? → 直前のものが0回または1回。-? ならマイナスがあってもなくてもOK
-
- → 直前のものが1回以上。\d+ なら数字が1桁以上
- \d → 数字1文字
- \ → 記号を文字そのものとして扱う。. は正規表現では特別な意味があるので、普通の「.」を探すなら .