为什么这个正则表达式替换不适用于JavaScript,而只适用于其他引擎? [英] Why does this regex replacement not work for JavaScript, but instead only work for other engines?
问题描述
我想构建一个JavaScript函数,将文本转换为另一种格式,由此:
I want to build a JavaScript function that transforms text into another format, from this:
MATCH 1
1. [4-17] `public direct`
2. [18-29] `routing.key`
MATCH 2
1. [35-41] `direct`
2. [42-52] `routingkey`
对此:
MATCH 1: [Group 1: public direct] [Group 2: routing.key]
MATCH 2: [Group 1: direct] [Group 2: routingkey]
我一直在使用正则表达式替换在我的Chrome浏览器控制台中弄乱这段代码,但它不会取代任何东西。这是我尝试过的方法之一, a
是测试对象,问题在于第二次更换:
I've been messing with this code in my Chrome browser console using regex replacements, however it will not replace anything. Here is one of the approaches I've tried, a
is the test object, the problem is on the second replacement:
a = "MATCH 1 \n\
1. [4-17] `public direct` \n\
2. [18-29] `routing.key` \n\
MATCH 2 \n\
1. [35-41] `direct` \n\
2. [42-52] `routingkey`"
var repl = a.replace(/^(MATCH\s\d+)\s*/gm, "$1: ")
.replace(/(\d+)\.\s+\[[^]]+\]\s*`([^`]*)`\s*/g, "[Group $1: $2]")
.replace(/(?=MATCH\s\d+: )/g, "\n")
console.log(repl)
学习regex101演示,模式 /(\d +)\。\ s + \ [[^]] + \] \ * *`([^`] *)`\ s * / g
将在PHP(PCRE)中正确替换 和Python ,但不在JavaScript上。
Studying regex101 demos, the pattern /(\d+)\.\s+\[[^]]+\]\s*`([^`]*)`\s*/g
will replace properly in PHP (PCRE) and Python, but not on JavaScript.
为什么?
推荐答案
对于 PCRE 实现,一个关闭的方括号本身不需要转义,因为它是字符类中的第一个元字符。在JavaScript中, [^]
表示有效的字符类。
For PCRE implementations, a closing square bracket on its own does not need to be escaped since it is the first meta character inside of the character class. In JavaScript, [^]
represents a valid character class.
引自 PCRE文档:
结束默认情况下,方括号本身并不特殊。但是,如果设置了 PCRE_JAVASCRIPT_COMPAT 选项,则
单独的结束方括号会导致编译时错误。如果作为该类的成员需要结束
方括号,它应该是该类中的
第一个数据字符(在初始抑扬符之后,如果
存在)或使用反斜杠转义。
A closing square bracket on its own is not special by default. However, if the PCRE_JAVASCRIPT_COMPAT option is set, a lone closing square bracket causes a compile-time error. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.
因此,您需要转义此字符。
Therefore, you need to escape this character.
/(\d+)\.\s+\[[^\]]+\]\s*`([^`]*)`\s*/g
^^
这篇关于为什么这个正则表达式替换不适用于JavaScript,而只适用于其他引擎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!