Since VBScript doesn't support lookbehinds, I'm looking for an alternative solution.
I have the string '\E\F\'.
I want to replace \F\ with '~', but ONLY if it is not preceded by a \E.
After the substitution, I want '\E\F\' to be '\E\F\'.
If the string was 'randomText\F\', I would want it to look like 'randomText~' after the substitution.
Solution:
I just decided to StrReverse it and do a negative forward lookahead. It's not the most elegant solution, but it seems to work in this case.
Dim regEx, str1
str1 = StrReverse("The quick \F\ brown \E\F\ dog.")
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Pattern = "\\F\\(?!E\\)"
regEx.Global = True
ReplaceTest = regEx.Replace(str1, "%")
Positive and Negative LookbehindIt tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. (? <!a)b matches a “b” that is not preceded by an “a”, using negative lookbehind.
Show activity on this post. Javascript has support for only positive and negative lookahead with no support whatsoever for lookbehinds, but you can still mimic the latter in Javascript using callbacks.
Negative lookbehinds seem to be the only answer, but JavaScript doesn't has one. Consider posting the regex as it would look with a negative lookbehind; that may make it easier to respond. @WiktorStribiżew : Look-behinds were added in the 2018 spec. Chrome supports them, but Firefox still hasn't implemented the spec.
Regex Lookbehind is used as an assertion in Python regular expressions(re) to determine success or failure whether the pattern is behind i.e to the right of the parser's current position. They don't match anything. Hence, Regex Lookbehind and lookahead are termed as a zero-width assertion.
VBScript doesn’t support look-behind assertions. But try this:
(^.?|[^\\].|\\[^E])\\F\\
Or this:
(^.?|(?!\\E)..)\\F\\
Replace the match with $1~
(first submatch and ~
).
Here’s an explanation: In general there are two situations: If there is no or just one character before \F\
(^.?
), everything is ok. But if there are at least two characters before \F\
, we need to make sure, that these characters are not \E
. So we say, that the two preceeding characters are either
\
followed by any arbitrary character ([^\\].
), or\
followed by any character other then E
(\\[^E]
).That construct ensures that every other combincation except \E
is allowed.
The same applies to the second expression. But here we use the negative look-ahead assertion to ensure that the two characters before \F\
is not \E
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With