Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this regex replacement not work for JavaScript, but instead only work for other engines?

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`

To this:

MATCH 1: [Group 1: public direct] [Group 2: routing.key]
MATCH 2: [Group 1: direct] [Group 2: routingkey]

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)

Studying regex101 demos, the pattern /(\d+)\.\s+\[[^]]+\]\s*`([^`]*)`\s*/g will replace properly in PHP (PCRE) and Python, but not on JavaScript.

Why?

like image 637
Unihedron Avatar asked Sep 30 '22 19:09

Unihedron


1 Answers

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.

As quoted from the PCRE documentation:

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
               ^^

Working Demo

like image 155
hwnd Avatar answered Oct 04 '22 04:10

hwnd