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.
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.