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 to only validate text if it doesn't contain blacklisted words (across multiple lines)

How may I write a regex, that only matches, if the text doesn’t contain any forbidden words. I have written a regex to do exactly that with the word anyone as an example. Here it is:

^(?!.*\banyone\b).*$/gm.

This regex does the job for one line, however, I want it to validate multiple lines and either have them all pass, or have them all fail, if only one of them contains given word. What’s currently happening is, that if I have three lines and the first one contains the word for example "anyone" , then the second and third line still match. I, however, want them not to match if a single line doesn’t match.
This would be extremely useful to not accept text, that contains swearing for example, a filter for swearing of sorts.

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

How may I do this?
Thank you

>Solution :

Hey, This is a simple fix.
Your flags /gm, mean global and multiline. You can achieve your behaviour by treating your string as a single line. Multiline mode treats the anchors ^ and $ as the beginning and end of each individual line. In single-line mode however, these are treated as the beginning and end of the entire string respectively.

So your solution is to simply change /gm to /gs, s for single-line…

Feel free to ask if you have any further questions.

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