Alex Rivera | Logout

Regex for all strings not containing a string?

Asked 2009-12-28T21:47:31.563
31

Ok, so this is something completely stupid but this is something I simply never learned to do and its a hassle.

How do I specify a string that does not contain a sequence of other characters. For example I want to match all lines that do NOT end in '.config'

I would think that I could just do

.*[^(\.config)]$

but this doesn't work (why not?)

I know I can do

.*[^\.][^c][^o][^n][^f][^i][^g]$

but please please please tell me that there is a better way

Edit
Report

2 Answers

36

Your question contains two questions, so here are a few answers.

Match lines that don't contain a certain string (say .config) at all:

^(?:(?!\.config).)*$\r?\n?

Match lines that don't end in a certain string:

^.*(?<!\.config)$\r?\n?

and, as a bonus: Match lines that don't start with a certain string:

^(?!\.config).*$\r?\n?

(each time including newline characters, if present.

Oh, and to answer why your version doesn't work: [^abc] means "any one (1) character except a, b, or c". Your other solution would also fail on test.hg (because it also ends in the letter g - your regex looks at each character individually instead of the entire .config string. That's why you need lookaround to handle this.

answered 2009-12-28T22:00:05.763
0

I used Regexpal before finding this page and came up with the following solution when I wanted to check that a string doesn't contain a file extension:

^(.(?!\.[a-zA-Z0-9]{3,}))*$ I used the m checkbox option so that I could present many lines and see which of them did or did not match.

so to find a string that doesn't contain another "^(.(?!" + expression you don't want + "))*$"

My article on the uses of this particular regex

answered 2011-10-20T14:05:05.633

Your Answer