Sign up ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write the shortest function that takes one string, and returns a regular expression that matches anything EXCEPT the input string, in parenthesis. Escape necessary characters like Perl quotemeta.

Input:
  helloworld
Output:
  ([^h]|h[^e]|he[^l]|hel[^l]|hell[^o]|hello[^w]|hellow[^o]|hellowo[^r]|hellowor[^l]|helloworl[^d])
Input:
  */
Output:
  ([^\*]|\*[^\/])

See also:

share|improve this question
    
I would have thought that that could be done more concisely in regex. –  Peter Olson Jul 11 '11 at 5:47
    
The resulting regexes are somehow strange. E.g. The first one will match "x" or "hx" but not "xx". This is not "anything except the input". What do you really want to match? –  Howard Jul 11 '11 at 6:12
2  
Or ^(?!hello$)(.*)$ should work also (depending on the exact requirement - it matches anything which is not exactly "hello", i.e. "hello!" would match). –  Howard Jul 11 '11 at 7:13
    
actually the regex I wrote had a problem. But I think there's a way to do that –  JBernardo Jul 11 '11 at 7:18
1  
Your example output for 'helloword' doesn't match the string 'h' or '' –  Rob Jul 20 '11 at 2:15

2 Answers 2

up vote 2 down vote accepted

Python, 49 chars

import re
f=lambda x:'(^(?!%s$).*$)'%re.escape(x)

The answer matches anything but the input. It gives an output using conditional groups so is suited for the problem:

regular expression that matches anything EXCEPT the input string

The answer uses Howard's regex (fixing my regex)

You can use the same approach on Perl with a few less chars:

Perl, 40 38

sub f{'(^(?!'.quotemeta(pop).'$).*$)'}

Examples:

f('hello') -> (^(?!hello$).*$)

f('*/')    -> (^(?!\*\/$).*$)
share|improve this answer
    
You can save two by replacing $_[0] with pop. –  Howard Jul 11 '11 at 7:48
    
@Howard that's right. But as the question asks for parenthesis in the answer, I added 2 chars too :) –  JBernardo Jul 11 '11 at 7:54
    
You only need the parenthesis only once, either around the statement or around .*. –  Howard Jul 11 '11 at 8:03

JAVA 61

String f(String w){return "^(?!"+Pattern.quote(w)+"$)(.*)$";}
share|improve this answer
    
String f(String w){return "^(?!\\Q"+w+"\\E)(.*)$";} –  Prince John Wesley Jul 21 '11 at 10:34
1  
@john that doesn't escape \E in the input string –  ratchet freak Jul 21 '11 at 11:54
    
yes. make sense.+1 –  Prince John Wesley Jul 21 '11 at 11:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.