2

I am trying to create a regex that should match following cases. if exact match of words 'first, second, third' then match should fail - but if there are any characters around it, then the string should be matched.

Also I need to avoid certain set of characters in the string. [()!=<>", ] - if these characters are part of string then match result should fail.

I looked at few examples & negative look ahead but did not get the right regex yet.

^(?!first$|second$|third$|fou rth$)[^()!=<>", ]+

desired output:

first - fail
second - fail
1first - pass
first1 - pass
1first1 - pass
fou rth - fail - it has space in between word and is from ignore list
newTest - pass
new(test - fail - since ( is not allowed character
space word - fail - since space is non allowed character

The regex needs to support case insensitive words

Any help appreciated. I am using javascript.

1 Answer 1

3

Try this Regex:

^(?!.*[()!=<>", ])(?!(?:first|second|third)$).+$

Click for Demo

Explanation:

  • ^ - asserts the start of the string
  • (?!.*[()!=<>", ]) - negative lookahead to validate that the test string does not contain any of these characters - (, ), !, =, <, >, ,,
  • (?!(?:first|second|third)$) - At this moment we are at the beginning of the test string. This position should not be immediately followed by (first or second or third) and then by the end of the string($)
  • .+ - matches 1+ occurrences of any character but not a newline character
  • $ - asserts the end of the string
Sign up to request clarification or add additional context in comments.

1 Comment

To the person who has down-voted, would you mind explaining your reason?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.