88

I have something like this

aabbabcaabda

for selecting minimal group wrapped by a I have this /a([^a]*)a/ which works just fine

But i have problem with groups wrapped by aa, where I'd need something like /aa([^aa]*)aa/ which doesn't work, and I can't use the first one like /aa([^a]*)aa/, because it would end on first occurence of a, which I don't want.

Generally, is there any way, how to say not contains string in the same way that I can say not contains character with [^a]?

Simply said, I need aa followed by any character except sequence aa and then ends with aa

finnw
  • 47,861
  • 24
  • 143
  • 221
Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327

7 Answers7

229

By the power of Google I found a blogpost from 2007 which gives the following regex that matches string which don't contains a certain substring:

^((?!my string).)*$

It works as follows: it looks for zero or more (*) characters (.) which do not begin (?! - negative lookahead) your string and it stipulates that the entire string must be made up of such characters (by using the ^ and $ anchors). Or to put it an other way:

The entire string must be made up of characters which do not begin a given string, which means that the string doesn't contain the given substring.

gp_sflover
  • 3,460
  • 5
  • 38
  • 48
Grey Panther
  • 12,870
  • 6
  • 46
  • 64
  • 10
    According to the docs, this is negative lookahead, not lookbehind – Luigi Plinge Jun 25 '12 at 00:52
  • (from the cited blog) full regexp ref: http://www.regular-expressions.info/refadv.html – Juh_ Aug 01 '13 at 16:43
  • 1
    The exact solution for the question is: `^aa(?!.*aa.*aa).*aa$` i.e. start by **aa**, look ahead and discard selections that follow with **[anything]aa[anything]aa**, and finish by **aa** – Juh_ Aug 01 '13 at 16:59
  • In place of the period, you can match past a single line with something like this: `^((?!my string)(\s|\S))*$` – daleyjem Aug 24 '16 at 22:25
  • @daleyjem - yes, that's correct - using `(\s|\S)` instead of `.` is a workaround for when you can't specify regex flags such as `s` (dot matches anything - including newline). – Grey Panther Aug 25 '16 at 10:59
  • 1
    I suppose it depends on the engine? According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes), dot doesn't recognize line terminators in Javascript. SublimeText's "find/replace" RegEx doesn't match newlines with dot either. – daleyjem Aug 25 '16 at 15:09
  • I used to think of myself as Regex Jedi until I came upon on this problem. –  Nov 30 '17 at 06:01
19

In general it's a pain to write a regular expression not containing a particular string. We had to do this for models of computation - you take an NFA, which is easy enough to define, and then reduce it to a regular expression. The expression for things not containing "cat" was about 80 characters long.

Edit: I just finished and yes, it's:

aa([^a] | a[^a])aa

Here is a very brief tutorial. I found some great ones before, but I can't see them anymore.

Claudiu
  • 224,032
  • 165
  • 485
  • 680
11

All you need is a reluctant quantifier:

regex: /aa.*?aa/

aabbabcaabda   => aabbabcaa

aaaaaabda      => aaaa

aabbabcaabda   => aabbabcaa

aababaaaabdaa  => aababaa, aabdaa

You could use negative lookahead, too, but in this case it's just a more verbose way accomplish the same thing. Also, it's a little trickier than gpojd made it out to be. The lookahead has to be applied at each position before the dot is allowed to consume the next character.

/aa(?:(?!aa).)*aa/

As for the approach suggested by Claudiu and finnw, it'll work okay when the sentinel string is only two characters long, but (as Claudiu acknowledged) it's too unwieldy for longer strings.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • 1
    I think our way is the only method that'll work with a non-backtracking implementation ( http://swtch.com/~rsc/regexp/regexp1.html ), but yeah, it is terribly annoying. I just don't know regex well enough to know about these lookahead things =). – Claudiu Apr 05 '09 at 14:04
  • Most modern regex flavors, especially those built into programming languages, are of the backtracking, NFA type. Even JavaScript, one of the least featureful flavors, supports lookaheads and reluctant quantifiers. http://www.regular-expressions.info/refflavors.html – Alan Moore Apr 05 '09 at 18:23
7
/aa([^a]|a[^a])*aa/
finnw
  • 47,861
  • 24
  • 143
  • 221
6

I'm not sure it's a standard construct, but I think you should have a look on "negative lookahead" (which writes : "?!", without the quotes). It's far easier than all answers in this thread, including the accepted one.

Example : Regex : "^(?!123)[0-9]*\w" Captures any string beginning by digits followed by letters, UNLESS if "these digits" are 123.

http://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx#grouping_constructs (microsoft page, but quite comprehensive) for lookahead / lookbehind

PS : it works well for me (.Net). But if I'm wrong on something, please let us know. I find this construct very simple and effective, so I'm surprised of the accepted answer.

AFract
  • 8,868
  • 6
  • 48
  • 70
4

I the following code I had to replace add a GET-parameter to all references to JS-files EXCEPT one.

<link rel="stylesheet" type="text/css" href="/login/css/ABC.css" />
<script type="text/javascript" language="javascript" src="/localization/DEF.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/GHI.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/md5.js"></script>
sendRequest('/application/srvc/EXCEPTION.js', handleChallengeResponse, null);
sendRequest('/application/srvc/EXCEPTION.js",handleChallengeResponse, null);

This is the Matcher used:

(?<!EXCEPTION)(\.js)

What that does is look for all occurences of ".js" and if they are preceeded by the "EXCEPTION" string, discard that result from the result array. That's called negative lookbehind. Since I spent a day on finding out how to do this I thought I should share.

jsaddwater
  • 1,781
  • 2
  • 18
  • 28
3
".*[^(\\.inc)]\\.ftl$"

In Java this will find all files ending in ".ftl" but not ending in ".inc.ftl", which is exactly what I wanted.

canadian_scholar
  • 1,315
  • 12
  • 26
twopigs
  • 31
  • 1
  • 2
    `[]` split `inc` into `i`, `n`, `c`. So it is false with both `"a.i.ftl".matches(".*[^(\\.inc)]\\.ftl$")` and `"a.inc.ftl".matches(".*[^(\\.inc)]\\.ftl$")`. –  Nov 07 '12 at 11:20