Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex: match 8 character words containing at least 3 instances of a digit or a specific symbol

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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*

Regex demo

Or using a capture group:

(^|\s)(?=\S{8}\s)(?:[^\s\d%]*[%\d]){3}\S*

Regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading