3

I'm trying to put together a regex pattern that matches a string that does contain the word "front" and does NOT contain the word "square". I have can accomplish this individually, but am having trouble putting them together.

front=YES

 ^((?=front).)*$

square=NO

 ^((?!square).)*$

However, how to I combine these into as single regex expression?

Andrew Hall
  • 139
  • 7
  • Does this answer your question? [Regular expression for a string containing one word but not another](https://stackoverflow.com/questions/2953039/regular-expression-for-a-string-containing-one-word-but-not-another) – oguz ismail May 28 '21 at 06:28

2 Answers2

6

You can use just a single negative lookahead for this:

/^(?!.*square).*front/

RegEx Demo

RegEx Details:

  • ^: Start
  • (?!.*square) is negative lookahead to assert a failure if text square is present anywhere in input starting from the start position
  • .*front will match front anywhere in input
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks for this! what if I wanted to test if it DID contain them both, in any order? – Andrew Hall Aug 01 '16 at 17:12
  • `if it DID contain them both, in any order` then use **`/^(?=.*square)(?=.*front)/`** – anubhava Aug 01 '16 at 17:16
  • 1
    I understand your answer is order independent, the change is that now I WANT square. Can I just remove the exclamation point?.....SEE your edit....thanks! – Andrew Hall Aug 01 '16 at 17:18
  • I agree that is the correct answer. But if you need "front" to be at the start of the string, you could use this: `/^(?!.*square)front/` – JMichaelTX Aug 01 '16 at 21:45
0

You could use lookahead assertions to express the logical and:

The final pattern would look like that:

^(?=.*?front)(?!.*square)
Rafael Albert
  • 445
  • 2
  • 8