Regular Expressions 101

use-capture-groups-to-search-and-replace

0

Regular Expression
ECMAScript (JavaScript)

/
(\w+)(\s)(\w+)\2(\w+)
/
igm

Description

(\w+)(\s)(\w+)\2(\w+)

in this exercise we have to use capture groups and then replace the string order to 'three two one'. But first, when you are using the capture group you may have asked yourself why the code below does not work:

(\w+)(\s)\1\2\1

to match the sting "one two three" this is because when you do a matching group he turns himself into a variable that capture the last value from regex and try to match again the same value not the regex itself. In the assertion above, were not simple doing : one two three (\w+)(\s)\1\2\1 = (\w+)(\s)(\w+)(\s)(\w+) word space word space word

but we're doing: one two three (\w+)(\s)\1\2\1 one space one space one

because the \1 aways will return the value 'one' and try to match it. So to resolve this, you have to have a capture group for EACH different word.

Submitted by gabriel silva lima - 9 months ago