Regex: How to remove a character before a matching string?

I intercept messages containing the following characters:

*_-

However, whenever any of these characters pass, it will always be preceded \. \is for formatting only, and I want to remove it before sending it to my server. I know how easy it is to create a regex that removes this backslash from a single letter:

'omg\_bbq\_everywhere'.replace(/\\_/g, '')

And I understand that I can just perform this operation 3 times: once for each character I want to delete the previous backslash. But how can I create one regex that detects all three characters and removes the previous backslash in all three cases?

+4
source share
2 answers

You can use a character class, for example [*_-].

To remove only the backslash before these characters:

document.body.innerHTML =
   "omg\\-bbq\\*everywhere\\-".replace(/\\([*_-])/g, '$1');
Run code

When you put a subpattern in the capture group ( (...)), you capture this subtext into a numbered buffer, and then you can reference it using $1backreference (1, because there is only one (...)in the template.)

+3
source

This is the right time to use atomic matching. In particular, you want to check for a slash, and then a positive result for any of these characters.

Ignoring the code, the raw regular expression:

\\ (? = [* _-])

A literal backslash with one of these characters in front of it: * _-

, . - 0, , , " , [* _-]"

: http://www.regular-expressions.info/atomic.html

: http://www.regular-expressions.info/lookaround.html

lookahead lookbehind.

+1

Source: https://habr.com/ru/post/1627489/


All Articles