User Tools

Site Tools


vba:functions:escaperegexppattern

[VBA] escapeRegExpPattern()

Escapte alle Sonderzeichen um einen rx-Pattern zu erstellen

Version 1.0.0 07.04.2016

Beispiele

?escapeRegExpPattern("Hallo Welt. Geht es dir (noch) gut?")
Hallo Welt\. Geht es dir \(noch\) gut\?

Code

udf_escaperegexppattern.bas
Attribute VB_Name = "udf_escapeRegExpPattern"
'-------------------------------------------------------------------------------
'File         : udf_escapeRegExpPattern.bas
'               Copyright mpl by ERB software
'               All rights reserved
'               http://wiki.yaslaw.info/dokuwiki/doku.php/vba/functions/escapeRegExpPattern
'Environment  : VBA 2010 +
'Version      : 1.0.0
'Name         : escapeRegExpPattern
'Author       : Stefan Erb (ERS)
'History      : 07.04.2016     Created
'-------------------------------------------------------------------------------
Option Explicit
 
'/**
' * Escapte alle Sonderzeichen um eine rx-Pattern zu erstellen
' *
' *     string = escapeRegExpPattern(string)
' *
' * @example    escapeRegExpPattern("Hallo Welt. Geht es dir (noch) gut?")
' *             Hallo Welt\. Geht es dir \(noch\) gut\?
' * @param  String
' * @return String
' */
Public Function escapeRegExpPattern(ByVal iPattern As String) As String
    Static rx As Object: If rx Is Nothing Then Set rx = cRx("/([\\\*\+\?\|\{\[\](\)\^\$\.\#])/g")
    escapeRegExpPattern = rx.Replace(iPattern, "\$1")
End Function
 
'/**
' * Dies ist die Minimalversion von cRegExp
' * http://wiki.yaslaw.info/dokuwiki/doku.php/vba/cast/cregexp#abgespeckte_version
' * mögliche Delemiter: @&!/~#=\|
' * mögliche Modifiers: g (Global), i (IgnoreCode, m (Mulitline)
' *
' * @example    myRx = cRx("/([a]{2,})/i") 'Finde alle folgen von a. Flag:IgnoreCase
' * @version    2.1.0 (01.12.2014)
' * @param      String      Pattern mit Delimiter und Modifier analog zu PHP
' * @return     Object      RegExp-Object
' */
Private Function cRx(ByVal iPattern As String) As Object
    Static rxP As Object:       Set cRx = CreateObject("VBScript.RegExp")
    If rxP Is Nothing Then:     Set rxP = CreateObject("VBScript.RegExp"): rxP.pattern = "^([@&!/~#=\|])?(.*)\1(?:([Ii])|([Gg])|([Mm]))*$"
    Dim sm As Object:           Set sm = rxP.execute(iPattern)(0).subMatches
    cRx.pattern = sm(1):        cRx.IgnoreCase = Not isEmpty(sm(2)):       cRx.Global = Not isEmpty(sm(3)):     cRx.Multiline = Not isEmpty(sm(4))
End Function
 
 

Discussion

Enter your comment. Wiki syntax is allowed:
If you can't read the letters on the image, download this .wav file to get them read to you.
 
vba/functions/escaperegexppattern.txt · Last modified: 12.12.2016 15:49:58 by yaslaw