I want a regex that will match anytype of below-mentioned texts:
[test]
test
test test
Should not match:
123
<spaces> test
%^&&
hi&**
^gello
So far I have tried this: ^[a-zA-Z][a-zA-Z\s]*$
This seems like a job for the often overlooked \b meta, which acts has a word-delimiter identifier: works for punctuation, spaces, brackets (and also parenthesis, square brackets, ... you got the idea)
Here’s the pattern: \btest\b it’s as simple as that ;-)
What about just
^(\[test\]|test|test test)$
Otherwise you'll need to be more clear what you want to match.
You can test and explain it using regex101.com
Marco Alka
Software Engineer, Technical Consultant & Mentor
If you want to match these examples, plus assuming quite a lot about what you want, this will match any white-space separated list of words, which allows brackets around words.
/^((^|[^^\d\W]\s|[^^]\]\s)(\[(?=[a-z]+\]))?[a-z]+\]?(\s(?=[a-z]))?)+$/iDon't forget to trim your input 😉 Note: It has some flaws: Currently, JS does not support positive look-behinds and named capturing groups (or alternatively recursing groups), so it unfortunately also matches "[test] abc]" and might glitch in edge-cases.
You can go to Regex101 and run the unit tests I set up or test any string in the test area to see if everything is all right.