I am trying to replace a portion of a text that is between apostrophes, not all, just a part.
For example, I need to replace the characters /* and */ that are only within text between quotes by null text but not outside them.
My input text, for example:
A = 'THIS IS AN ALPHABETIC /* CONSTANT' || WS_CON1 /* */ || 'TEST STRING */';
Expected output:
A = 'THIS IS AN ALPHABETIC CONSTANT' || WS_CON1 /* */ || 'TEST STRING ';
I extracted the texts in quotes but I do not know how to replace the /* and */ with null text.
Sub ReplaceWithRegex()
Dim strPattern As String
Dim strReplace As String
Dim regEx As Variant
Dim strtxt As String
Set regEx = CreateObject("vbscript.regexp")
strtxt = "A = 'THIS IS AN ALPHABETIC /* CONSTANT' || WS_CON1 /* */ || ' TEST STRING */';"
strPattern = "\'([^\']*)\'"
strReplace = ""
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strtxt) Then
Debug.Print regEx.Replace(strtxt, strReplace)
Else
MsgBox ("Not matched")
End If
End Sub
Obviously, this replace all text between quotes to null string.
How do I solve this problem?
Answer
Here is another VBA method using Regular Expressions.
Option Explicit
'Set Reference to Microsoft VBScript Regular Expressions 5.5
Function reReplaceComment(S As String) As String
Dim RE As RegExp
Dim I As Long, J As Long
Set RE = New RegExp
With RE
.Global = True
.Pattern = "('[^']*?)(?:(?:/\*)|(?:\*/))([^']*?')"
reReplaceComment = .Replace(S, "$1$2")
End With
End Function
Remove tokens within single quotes
('[^']*?)(?:(?:/\*)|(?:\*/))([^']*?')
$1$2
Created with RegexBuddy
No comments:
Post a Comment