How can I exclude a string anyhwere in the pattern from matches?
I need to write a regex which will match URLs that do not have a specific query string name/value pair anywhere in its URL. All other query string names, and all other query string values with the same name should be matched. Other pages in the same directory (or sub-directories) should not be matched.
For example, suppose the base URL that I need to match is:
http://www.domain.com/directory/
The query string name and value that I need to exclude from matches is:
fred=f
So far, I’ve got:
http://www\.domain\.com/directory/(?!(\?|&)fred=f$)
Which matches:
- http://www.domain.com/directory/
- http://www.domain.com/directory/?fred=a
- http://www.domain.com/directory/?fred=foo
But not:
- http://www.domain.com/dir开发者_开发技巧ectory/?fred=f
The problem is that this regex also matches:
- http://www.domain.com/directory/?foo=bar&fred=f
If I use this regex instead:
(?i)http://www\.domain\.com/directory/[a-z]*(?!(\?|&)fred=f$)
Then this URL is matched:
- http://www.domain.com/directory/foobar?fred=f
(It seems that the [a-z] is stronger than the disallow group.)
How can I prevent matches when the string exists anywhere in the pattern?
(This will be used in an ActionScript3/ECMAScript3 regex engine.)
Is there any reason you need to use a regex? Why not just a simple string search? It does exactly the same thing, buts easier to understand.
myString.search("fred=f");
Tyler.
One of my colleagues provided the basis for this answer:
http://www.domain.com/directory/(?!.*(\?|&)fred=f($|&|#))(\?|#|$)
This regex matches:
http://www.domain.com/directory/
http://www.domain.com/directory/?fred=a
http://www.domain.com/directory/?fred=foo
http://www.domain.com/directory/?foo=bar
but not:
http://www.domain.com/directory/?fred=f
http://www.domain.com/directory/?fred=f&a=b
http://www.domain.com/directory/?a=b&fred=f
EDIT: Changed the expression. Previous version was limited to 99 characters.
EDIT2: Improved the expression, now matches more cases.
I have made something like this
(domain.com/directory/.*fred=(?!f$)(?!f&).*)|(domain.com/directory/$)|(domain.com/directory/\?(?!.*fred=f).*)
and tested it on the following strings
- domain.com/directory/?foo=f&bar=f
- domain.com/directory/?foo=bar
- domain.com/directory/?aaa=bar
- domain.com/directory/
- domain.com/directory/?fred=a
- domain.com/directory/?fred=foo
- domain.com/directory/?foo=bar&fred=foo
- domain.com/directory/?fred=f&aaaw=bbb
- domain.com/directory/?fred=f
- domain.com/directory/?foo=bar&fred=f
My regexp matched the ones in bold. I have tested it at www.RegexTester.com
精彩评论