VBScript 的正则表达式负回溯替代方案 [英] Regular Expression Negative Lookbehind Alternative for VBScript
问题描述
由于 VBScript 不支持后视,我正在寻找替代解决方案.
Since VBScript doesn't support lookbehinds, I'm looking for an alternative solution.
我有字符串 '\E\F\'.
I have the string '\E\F\'.
我想用'~'替换\F\,但前提是它前面没有\E.
I want to replace \F\ with '~', but ONLY if it is not preceded by a \E.
替换后,我希望 '\E\F\' 为 '\E\F\'.
After the substitution, I want '\E\F\' to be '\E\F\'.
如果字符串是'randomText\F\',我希望它在替换后看起来像'randomText~'.
If the string was 'randomText\F\', I would want it to look like 'randomText~' after the substitution.
解决方案:
我只是决定对它进行 StrReverse 并做一个负面的前瞻.这不是最优雅的解决方案,但在这种情况下似乎有效.
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, "%")
推荐答案
VBScript 不支持外观-在断言背后.但是试试这个:
(^.?|[^\\].|\\[^E])\\F\\
或者这个:
(^.?|(?!\\E)..)\\F\\
将匹配替换为 $1~
(第一个子匹配和 ~
).
Replace the match with $1~
(first submatch and ~
).
这里解释一下:一般有两种情况:如果\F\
(^.?
)前没有或只有一个字符,则一切正常.但是如果\F\
之前至少有两个字符,我们需要确保这些字符不是\E
.所以我们说,前面的两个字符要么是
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
- 除
\
外的任何字符后跟任意字符([^\\].
),或 \
后跟除E
之外的任何字符(\\[^E]
).
- any character except
\
followed by any arbitrary character ([^\\].
), or \
followed by any character other thenE
(\\[^E]
).
该构造确保允许除 \E
之外的所有其他组合.
That construct ensures that every other combincation except \E
is allowed.
同样适用于第二个表达式.但是这里我们使用否定的前瞻断言来确保\F\
之前的两个字符不是\E
.
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
.
这篇关于VBScript 的正则表达式负回溯替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!