Excel VBAの正規表現についての疑問

このQ&Aのポイント
  • ExcelでVBScriptの正規表現を使用しているが、理解できない箇所がある。
  • 具体的には、検索パターンが「AAA.+bbb」でありながら、AAA111BBBが表示されないことに疑問を持っている。
  • 質問の内容を解決するため、Excel VBAの正規表現について詳しく教えてほしい。
回答を見る
  • ベストアンサー

正規表現について

ExcelにてVBScriptの正規表現を使用していますが、 理解できないところがあるので、教えてください 1.EXCEL VBAにて下記のコードがあります Sub Sample2() Const strCHK As String = "000AAA111BBB2222BBB333" Dim RE, strPattern As String, i As Long, msg As String, reMatch, Item Set RE = CreateObject("VBScript.RegExp") strPattern = "AAA.+bbb" With RE .Pattern = strPattern .IgnoreCase = True .Global = True Set reMatch = .Execute(strCHK) For Each Item In reMatch Debug.Print Item.Value & " FirstIndex→" & Item.FirstIndex & " Length→" & Item.Length Next End With Set reMatch = Nothing Set RE = Nothing End Sub 2.上記を動作させると、イミディエイトに下記が出力されます AAA111BBB2222BBB FirstIndex→3 Length→16 3.疑問 strPattern = "AAA.+bbb"にて検索しているのに、 AAA111BBBが表示されないのは、何故なのでしょうか? よろしくお願いします

  • Koba5
  • お礼率81% (96/118)

質問者が選んだベストアンサー

  • ベストアンサー
  • morchin
  • ベストアンサー率16% (212/1281)
回答No.1

貪欲マッチしているからでは? 最短マッチにする必要があります。 試していませんが、 strPattern = "AAA.+?bbb" では、どうですか?

Koba5
質問者

お礼

morchinさん 早速のコメrントありがとうございます 指摘とおりでした

関連するQ&A

  • 【VBA】【正規表現】

    23歳OLです。 VBAと正規表現についての質問です。 ▼やりたいこと ================================================ 1 | 0 |1234567890 | 2014-2-22 22:22:22.06+09 という数列から 1234567890 という数字のみを抜き出したいです。 正確には2本目の|と3本目の|の間に入っている様々な数字です。 ※桁数が固定されていません。 ================================================ ▼実際書いたコード ================================================ Sub Sample2() Dim RE, strPattern As String, i As Long, msg As String, reMatch Set RE = CreateObject("VBScript.RegExp") strPattern = "☆この部分☆" With RE .Pattern = strPattern .IgnoreCase = True .Global = True For i = 1 To 10 Set reMatch = .Execute(Cells(i, 1)) If reMatch.Count > 0 Then msg = msg & reMatch(0).Value & vbCrLf End If Next i End With MsgBox msg Set reMatch = Nothing Set RE = Nothing End Sub ================================================ ☆この部分に☆に何を入れればよいでしょう? ご指導よろしくおねがいします。

  • 文字列中の両丸括弧を取り除くVBA正規表現

    文字列中の両括弧を取り除く正規表現を求めています. 入力文は「(文字列1)文字列2」となっています. 両括弧は全角の丸括弧"(",")"と半角の丸括弧"(",")"のペアを見つけ,文字列2を取り出したいのです. 文字列1,文字列2は全角,半角の文字列(主に全角)が来ます.括弧の中に括弧が入れ子(ネスト)する事は想定していません. 例えば,「(グループA)田中」という入力に対しては,「田中」をExcel VBAで抽出したいのです. 正規表現ライブラリを使っていますが,別の方法でも効率良く抽出できるならOKです. '---------------  以下を試した結果  --------------------------------- Dim RE, strPattern As String, reMatch Set RE = CreateObject("VBScript.RegExp") ' 'strPattern = "^(\(|().*(\)|))$" ' 'strPattern = "(?!.*[(|\(].+?[\)|)])" ' "(グループA)"にマッチする ' 'strPattern = "([\(.+?\)|(.+?)])" ' 'strPattern = "(^[(|\(].+?[\)|)])" ' strPattern = "^(?!.*[(|\(].+?[\)|)])" ' "" ' 'strPattern = "\(.+?\)" ' strPattern = "^(?!.*[\(.+?\)|(.+?)])" ' "" ' strPattern = "(?!.*[(.+?)])" ' "" ' strPattern = "(.+?)" ' "(グループA)"にマッチする ' strPattern = "^[?!.*((.+?))]" ' ' strPattern = "[^((.+?))]" ' ' '.Pattern = "^(?!.*xyz)" ' 'strPattern = "^(?!.*([.+?]))" ' "" ' strPattern = "[^(.*)]" '"グ","ル",,, ' strPattern = "^(?!([.*]).*)" ' "" ' strPattern = "^(?!(.*).*)" ' "" ' strPattern = "^(?!([.*]))" ' "" strPattern = ").*$" ' "" With RE .Pattern = strPattern .IgnoreCase = True .Global = True Set reMatch = .Execute(str) If reMatch.Count > 0 Then str = reMatch(0).Value End If End With '開放 Set reMatch = Nothing Set RE = Nothing

    • ベストアンサー
    • CSS
  • エクセル マクロ 英語のデータから検索

    どなたかご教示頂ければ幸いです。 以下のようなデータがある場合に、 Japanese team Made in Japan in the Japanese music scene American team Made in USA in the American music scene 次のようなVBAを作りました。 Sub macro1() Dim re, strpattern As String, i As Long, msg As String, rematch Set re = CreateObject("vbscript.regexp") strpattern = "japan.*" With re .Pattern = strpattern .ignorecase = True .Global = True For i = 1 To 10 Set rematch = .Execute(Cells(i, 1)) If rematch.Count > 0 Then msg = msg & rematch(0) & vbCrLf End If Next i End With MsgBox msg Set rematch = Nothing Set re = Nothing End Sub すると、msgボックスには Japanese team Japan Japanese music sceneと表示されます。 私はヒットしたセルの内容を、以下のように全て表示させたいと思っております。 Japanese team Made in Japan in the Japanese musci sceneと・・・ どうすればよろしいでしょうか? 是非とも宜しくお願い申し上げます。

  • vbaでの正規表現について教えてください

    「セルに入ってる値が数値ならA列からE列まで赤色にする」 を正規表現で行いたいのですがよくわかりません。 http://officetanaka.net/excel/vba/tips/tips38.htm を参考にしているのですが Sub Sample1() Dim RE, strPattern As String, r As Range Set RE = CreateObject("VBScript.RegExp") strPattern = "SUM\(" With RE .Pattern = strPattern ''検索パターンを設定 .IgnoreCase = True ''大文字と小文字を区別しない .Global = True ''文字列全体を検索 For Each r In ActiveSheet.UsedRange If .test(r.Formula) Then r.Interior.ColorIndex = 3 Next r End With Set RE = Nothing End Sub を、どう改造すれば、私のやりたい事になるのでしょうか? 【1】 まずstrPattern で、「数値ならば」はどうやればいいでしょうか? 【2】 次にtest(r.Formula)は、数式だからFormulaを使ってるのですよね? 数値を検索する場合はFormulaを何に変えればいいでしょうか? 【3】 最後に、 r.Interior.ColorIndex = 3はそのセルだけの色を変えるのですよね? A列からE列までにするにはどうすればいいでしょうか? 例えば A3セルに「1」が、A6セルに「3」が入っていたら、 A列からE列まで赤色にしたいです。

  • Excel : 正規表現を利用して2文字の全角数字を半角数字に変換するには?

    アクティブセルの文字を、正規表現を利用して文字の変換をしたいと考えています。 2文字の全角数字を半角数字に変換します。 かつ、3文字以上の全角数字は変換しません。 下記のようにコードを書いたのですが、希望通りに動作してくれません。 どこが悪いのでしょうか? ご指摘いただければ幸いです。 よろしくお願いいたします。 ※参照可能なライブラリファイルにて、「Microosft VBScript Regular Expressions 5.5」に  チェックは入れています。 Sub sample()   Dim str   Dim strPattern As String   Dim strReplacement As String      str = ActiveCell.Value   str = myRegExp(str, "([^0123456789])([0123456789]{2})([^0123456789])", "$1$2$3")   ActiveCell.Value = str End Sub Private Function myRegExp(str, strPattern, strReplacement)   Dim objRegExp As RegExp   Dim test As String   Set objRegExp = New RegExp   With objRegExp     .Pattern = strPattern     .IgnoreCase = False     .Global = True     myRegExp = .Replace(str, "$1" & StrConv("$2", vbNarrow) & "$3")   End With   Set objRegExp = Nothing End Function

  • VBAの正規表現で特定のフレーズの出現回数を数えるには?

    VBスクリプトでの正規表現について質問します。 例として、次のようなプログラムを作成し、メッセージボックスに"2回"と表示されるような結果を期待しているのですが、"1回"と表示されて困っています。2回と表示されるようにするには、どのようにすればよいのでしょうか?アドバイスをお願いします。 Dim objRegex, objMatches, objMatch As Object Dim intRslt As Integer Dim strSource,strPattern As String Set objRegex = CreateObject("VBScript.RegExp") strSource = "お米の国と呼ばれる日本。お米のお国処は、秋田" strPattern ="お米.*国" With objRegex .Pattern = strPattern .ignorecase = True '.Global = True End With Set objMatches = objRegex.Execute(strSource) intRslt = objMatches.Count msgbox(intRslt & "回") エクセルに使用するため、"VBScript.RegExp"での動作環境になります。

  • これは正規表現とは言えないでしょうか?

    正規表現を勉強しようと思っているのですが まずはじめに確認させて下さい。VBAです。 Sub 正規表現() If a Like "*a*" Then End If End Sub は正規表現とは言えないでしょうか? *を使っているからそう思いました。 Dim re As RegExp Set re = New RegExp を使わないと、正規表現といえないのでしょうか? よろしくお願い致します。

  • VBAの正規表現

    VBAで正規表現による置換をしたいです。 以下のような行が複数あります。 1 aaa bbb ccc ddd 2 aaa bbb ccc ddd 3 aaa bbb ccce ddd 4 aaa bbb eccc ddd ccc の部分のみ置換したいです。 dim hensuu as string dim replace as string replace = eee hensuu = ccc (省略) strPattern = "(\s*)" & hensuu & "(\s+)" rep = RegExpObj.Replace(buf, "\1" & replace & "\2") 行数1,2 のみを置換したのですが、4も置換されてしまいます。 (\s*) の "*" が良くないのは理解していますが、"+" にしてもうまくいきません。 どなたかどのようにしたら1,2のみ置換できるようになるかをご教授お願いできませんでしょうか よろしくお願いいたします。

  • 正規表現でデーター取得

    Webクエリで株価取得しようマクロを作ったのですが IE7を使用しているので、出来ないことが分かり 正規表現にて取得しようとしてみましたが うまく取得できません。 http://www.technobahn.com/apps/fn/quote?r=3m&c=1412&s=medium&color=&lang= 上記リンク先の始値~相場全体までのデータを 取得したいのですが・・・ とりあえずは、取得したデータをsheet2.A列に入れてみたのですが 文字化けに関係のないデータまでもを取得しています。 sheet1  A     コード Const vaa As String = "Ver1.02" Const URLI As String = "http://www.technobahn.com/apps/fn/quote?r=3m&c=" Dim urlweb As String 'Web接続先 Dim code As String '銘柄コード Sub 株価取得() Dim oHttp As Object, ws1 As Object, ws2 As Object Dim dthtml As String Dim chktb As String Dim stchk1 As Long Dim stchk2 As Long Dim chksu As Long Dim j As Integer Dim urlweb As String Dim mino As Long, w As Long Set ws1 = Sheets(1) Set ws2 = Sheets(2) w = 1 mino = ws1.Cells(w, 1) urlweb = URLI & "mino" Set oHttp = CreateObject("Microsoft.XMLHTTP") oHttp.Open "GET", urlweb, False oHttp.Send dthtml = oHttp.responsetext With CreateObject("VBScript.RegExp") .Pattern = ">([^<>]+)<" .Global = True On Error Resume Next stchk1 = InStr(dthtml, "始値") stchk2 = InStrRev(Left(dthtml, stchk1), "table") chksu = InStr(stchk2, dthtml, "</table") dthtml = Mid$(dthtml, stchk2, chksu) itmsu = .Execute(dthtml).Count ReDim hdat(itmsu) With .Execute(dthtml) For j = 1 To itmsu ws2.Cells(j, 1) = .Item(j).SubMatches(0) Next j End With On Error GoTo 0 End With Set oHttp = Nothing DoEvents End Sub

  • ExcelのVBAの正規表現で二重引用符を含む文字列を検索できるようにしたい

    二重引用符を含む文字列を検索できるようにするには 下記の記述の re.Pattern = "<hr class=\"separate\">" の部分をどのように直せばよいのでしょうか? Sub tagCount() Dim cnt As Integer Dim IE As Object Dim HTML As String Set IE = CreateObject("InternetExplorer.Application") IE.Navigate ("http://www.yahoo.co.jp/") While IE.busy: Wend While IE.Document.readyState <> "complete": Wend HTML = IE.Document.body.innerHTML IE.Quit Dim re As RegExp Dim mc As MatchCollection Dim m As Match Set re = New RegExp re.Pattern = "<hr class=\"separate\">" re.Global = True re.IgnoreCase = True Set mc = re.Execute(HTML) MsgBox mc.Count End Sub ご存知の方がおられましたらご回答をよろしくお願いします。 使用OS:Windows XP 使用ソフト:Microsoft Excel 2003

専門家に質問してみよう