1

Using regex, I need to test that a string contains A. But the string cannot contain either B or C.

What is the REGEX syntax?

Sam Henderson
  • 479
  • 5
  • 7
  • 1
    The straightforward way to do this is with three regexes, honestly. It can be done with one, but it's really not pretty (and starts to vary by regex engine type). How you combine them depends on the language, but basically `(!/B/ && !/C/ && /A/)` – zzxyz May 05 '18 at 00:10
  • 1
    "Using regex" is incredibly vague; there are many different regex libraries, that define wildly varying syntax. (A lot of them borrow heavily from Perl regexes, but even among those there's a lot of variation.) So you need to say which one you're using. – ruakh May 05 '18 at 00:21
  • For PCRE, you can look at my first SO question: https://stackoverflow.com/questions/45762836/replace-a-string-when-two-strings-exist-in-one-regex-in-perl The answer uses lookarounds and you could replace a positive lookaround with negative to get the desired effect. Although it's worth noting that the answer doesn't actually work in Perl. (But it works with a lot of PCRE languages and "almost supersets" , such as .NET) – zzxyz May 05 '18 at 00:30

4 Answers4

2

You could use the following regex:

\b[^\sCB]*A[^\sCB]*\b

that will match any word containing A but not containing C or B

A regex to match words contaning bar but not containing car nor foo is:

\b(?!\S*(car|foo))\S*bar(?!\S*(car|foo))\S*\b

builder-7000
  • 7,131
  • 3
  • 19
  • 43
  • I assume he did not literally mean `A` `B` `C` but variables that could conceivably be longer than 1 character. Although I'm going to upvote this anyway since it technically answers the question and made me laugh. – zzxyz May 05 '18 at 00:27
  • Good point, OP may want something like `A=foo`, `B=bar`, `C=car`. If that is the case I'd probably use look-arounds and the regular expression would be more involved. – builder-7000 May 05 '18 at 00:42
  • 1
    I've included such regex in the answer. – builder-7000 May 05 '18 at 00:51
0

Actually...the following approach isn't too awful:

^(?!.*are)(?!.*how).*(hello)

If you don't want are or how but want hello. The parens around hello are optional and "captures" just the bit you want instead of the whole string.

https://regex101.com/r/FiO9QD/2

zzxyz
  • 2,953
  • 1
  • 16
  • 31
0

Try this:

^(?!.*[BC]).*A.*

I think this is the smallest regex that will do the job.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

If you want to check if the whole string contains A and not B or C you might use a negated character class to match not B, C or a newline.

^[^BC\n]*A[^BC\n]*$

Details

  • ^ Assert position at the start of the line
  • [^BC\n]* Match zero or more times not a B or C or newline
  • A Match literally
  • [^BC\n]* Match zero or more times not a B or C or newline
  • $ Assert position at the end of the line
The fourth bird
  • 154,723
  • 16
  • 55
  • 70