4

How can I match a string that is NOT partners?

Here is what I have that matches partners:

/^partners$/i

I've tried the following to NOT match partners but doesn't seem to work:

/^(?!partners)$/i
2
  • 2
    I don't know. But can't you just invert the result returned by whatever regex function you're using? Commented Dec 28, 2011 at 22:06
  • In what programming language? Commented Dec 28, 2011 at 22:09

4 Answers 4

9

Your regex

/^(?!partners)$/i

only matches empty lines because you didn't include the end-of-line anchor in your lookahead assertion. Lookaheads do just that - they "look ahead" without actually matching any characters, so only lines that match the regex ^$ will succeed.

This would work:

/^(?!partners$)/i

This reports a match with any string (or, since we're in Ruby here, any line in a multi-line string) that's different from partners. Note that it only matches the empty string at the start of the line. Which is enough for validation purposes, but the match result will be "" (instead of nil which you'd get if the match failed entirely).

Sign up to request clarification or add additional context in comments.

Comments

2

not easily but with the look ahead operator it can. Here the ruby regex

^((?!partners).)*$

Cheers

1 Comment

This matches any string that doesn't contain partners, which is possibly not what Jacob wanted. At least it's not what he asked for.
1

If you only want to get a true value when string is not partners then there is no need to use regex and you can just use a string comparison (which ignores case).

If you for some reason need a positive regex match for any string which does not contain partners (if it's a part of a larger regex for example) you could use several different constructs, like:

`^(?:(?!partners).)*$`

or

^(?:[^p]+|p(?!artners))*$

Comments

0

For example, in Java:

!"partners".equalsIgnoreCase(aString)

Comments

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.