如何在VBScript RegEx中用换行符进行替换

3

我正在使用VBScript,并拥有一个将xml转换为文本文件的脚本。

我想要进行替换,将字符串###EntryEnd###\|替换为LF字符。

我尝试在替换模式中使用\n\x0a,但它们都不起作用。我找到的唯一解决方法是使用Chr(10)

我寻求了关于这种行为的答案,但没有找到。\n\x0a都应该起作用。有什么建议吗?

以下是代码:

' Method to process the file
Private Function PrepFile(ByVal strInp)
    With New RegExp
        .Global = True
        .Pattern = "\|"
        strInp = .Replace(strInp, "")
        .Pattern = "<xmldoc .*?xml:lang=""([^""]+)"">"
        strInp = .Replace(strInp, "English|$1|Part Of Speech|Note|EngDef|Glossary Definition###EntryEnd###|")
        .Pattern = "<remove>.*?</remove>"
        strInp = .Replace(strInp, "")
        .Pattern = "(<tab/>|</para>)"
        strInp = .Replace(strInp, "|")
        .Pattern = "<[^>]*>"
        strInp = .Replace(strInp, "")
        .Pattern = "\n"
        strInp = .Replace(strInp, "")
        .Pattern = "###EntryEnd###\|"
        strInp = .Replace(strInp, chr(10))
    End With
    PrepFile = strInp
End Function

示例文件片段:

<?xml version="1.0" encoding="UTF-8"?>
<xmldoc source="" type="TERMS" xml:lang="hu-HU">
<para id="13" name="Entry"><notrans><seg>School Administrator</seg><tab/></notrans><remove>___________</remove><seg>iskolavezető</seg></para>
<para id="14" name="Usage"><notrans><seg> </seg><tab/></notrans><remove>HASZNÁLAT:</remove><seg> </seg></para>
<para id="15" name="EntryText"><notrans><seg> </seg><tab/></notrans><remove>MEGHATÁROZÁS:</remove><seg> </seg></para>
<para id="16" name="Context"><remove>PÉLDA:</remove><remove><seg>Cathy Brown iskolavezető</seg></remove><notrans>###EntryEnd###</notrans></para>
<para id="17" name="Entry"><notrans><seg>School Resource Officer</seg><tab/></notrans><remove>___________</remove><seg>iskolarendőr</seg></para>
<para id="18" name="Usage"><notrans><seg> </seg><tab/></notrans><remove>HASZNÁLAT:</remove><seg> </seg></para>
<para id="19" name="EntryText"><notrans><seg>a law enforcement officer who is responsible for providing security and crime prevention services in schools in parts of the United States and Canada.|</seg><tab/></notrans><remove>MEGHATÁROZÁS:</remove><seg>rendőr, aki azért felelős, hogy az iskolákban biztonsági és bűnmegelőzési feladatokat lásson az Egyesült Államok és Kanada egyes területein.</seg></para>
<para id="20" name="Context"><remove>PÉLDA:</remove><remove><seg>Ocalai iskolarendőrök</seg></remove><notrans>###EntryEnd###</notrans></para>
</xmldoc>
1个回答

2
在你的问题中,“问题”(简单错误的假设)可以在以下内容中找到:
  • Both \n and \x0a should work
Replace方法的文档没有说明替换字符串除了正则表达式模式中的$1$2之外允许使用转义序列。
因此,如果RegExp对象在替换字符串中不提供这种行为,并且由于VBScript解析器除了转义的双引号之外不处理字符串中的任何转义序列,所以没有任何元素处理\n到换行符的转换。
您可以使用指示的转义序列来表示搜索模式字符串中的非打印字符,但它们在替换字符串中不被视为转义序列。
如果您不喜欢Chr(10)函数调用,可以使用可用的vbLf常量来引用换行符。
strInp = .Replace(strInp, vbLf)

有趣。我找不到任何文件说明只有子表达式反向引用是允许的。当然,如果转义字符没有被处理,它们就不会起作用,但我想知道是否只有我认为基本的转义字符会起作用。我猜这是VB的缺点,而不是Regexp的缺点。 - ib11
1
@ib11,VBScript不处理字符串文字中的转义序列,这不是语言的一部分。RegExp Pattern属性可以使用转义序列。Replace方法使用一个替换字符串,此外还允许子表达式引用。 - MC ND

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接