I'm trying to check if a word exists in a string with regex and JavaScript but I'm struggling to get it right.
The matched string can only have a space or nothing before it. The matched string can't have alphanumeric characters or punctuation directly behind it. The matched string can't have alphanumeric characters straight after it, only !, , , ., a space, or nothing. Examples are below!
Currently my regex looks like this:
\w*(?<![^ ])\bHello\b
If you test Hello, Hello!, Hello or Hello it returns true as expected.
If you test .Hello, aHello or Helloa it returns false as expected.
However I have two problems:
- It returns true if you pass it
Hello:,Hello?,Hello)etc. which is not what I want, only!,,,.should be allowed. - It does not work for strings with punctuation - I will need to check if the strings
D:,:D, and<3exist in a sentence. I believe this is due to my use of\b
I tried converting \b into what it does under the hood and modifying that, but I couldn't get it to work how I wanted to so I have turned to StackOverflow. I'm OK with having a regex for alphanumeric strings and another one for strings with symbols like : and <. Or if you think it's best to just switch to manual checking with a JavaScript function then that's OK too.
Thanks for any help.