I’m trying to create a regex that matches 8 character words that contain at 3 least instances of a digit or the ‘%’ symbol and whitespace after the word.
The following strings should match:
- ‘ab1d2f3h ‘
- ‘ab%d2f3h ‘
- ‘ab%d%f3h ‘
- ‘ab%d%f%h ‘
The regex I have so far looks like this:
const string = 'this word ab1d2f3h needs to go, but not this word abcdefgh %%%'.replace(/(?=(?:\D*(\d|%)){3})(\w|%){8}\s/g, '%%%%%%%% ')
If I remove ‘%%%’ from the string, it works – ‘ab1d2f3h ‘ is replaced. However, if ‘%%%’ is present in the string, it also replaces ‘abcdefhg ‘, which I don’t want to happen.
Does anyone know the proper regex for this?
>Solution :
If a lookbehind assertion is supported in the environment where you are using the pattern:
(?<!\S)(?=\S{8}\s)(?:[^\s\d%]*[%\d]){3}\S*
Or using a capture group:
(^|\s)(?=\S{8}\s)(?:[^\s\d%]*[%\d]){3}\S*