chris lipsit
chris lipsit

Reputation: 1

Excluding URLS that contain a string in Regex

I am using regex to add a survey to pages and I want to include it on all pages except payment and signin pages. I can't use look arounds for the regex so I am attempting to use the following but it isn't working.

^/.*[^(credit|signin)].* Which should capture all urls except those containing credit or signin

Upvotes: 0

Views: 1553

Answers (2)

zzzzBov
zzzzBov

Reputation: 179266

Whitelisting words in regex is generally pretty easy, and usually follows a form of:

^.*(?:option1|option2).*$

The pattern breaks down to:

  • ^ - start of string
  • .* - 0 or more non-newline characters*
  • (?: - open non-capturing group
    • option1|option2 - | separated list of options to whitelist
  • ) - close non-capturing group
  • .* - 0 or more non-newline characters
  • $ - end of string

Blacklisting words in a regex is a bit more complicated to understand, but can be done with a pattern along the lines of:

^(?:(?!option1|option2).)*$

The pattern breaks down to:

  • ^ - start of string
  • (?: - open non-capturing group
    • (?! - open negative lookahead (the next characters in the string must not match the value contained in the negative lookahead)
      • option1|option2 - | separated list of options to blacklist
    • ) - close negative lookahead
    • . - a single non-newline character*
  • ) - close non-capturing group
  • * - repeat the group 0 or more times
  • $ - end of string

Basically this pattern checks that the values in the blacklist do not occur at any point in the string.

* exact characters vary depending on the language, so use caution


The final version:

/^(?:(?!credit|signin).)*$/

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191809

[ indicates the start of a character class and the [^ negation is per-character. Thus your regular expression is "anything followed by any character not in this class followed by anything," which is very likely to match anything.

Since you are using specific strings, I don't think a regular expression is appropriate here. It would be a lot simpler to check that credit and signin don't exist in the string, such as with JavaScript:

-1 === string.indexOf("credit") && -1 === string.indexOf("signin")

Or you could check that a regular expression does not match

false === /credit|signin/.test(string)

Upvotes: 1

Related Questions