简体   繁体   中英

javascript regex: string contains this, but not that

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?

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

You could use lookahead assertions to express the logical and:

The final pattern would look like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM