Click here to Skip to main content
15,867,991 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi all. I have small problem I have some input text. I want to match that text but only then, when it not contains some words. I know how to do similar thing with characters ([^ChArAcTeRsWhItChIdOnTwAnT]). So my question is: is there any way how to get text starting with some words and ending with some words but that text cannot contain specified word? Thanks.
Posted

You want a negative lookahead or a negative lookbehind. Suppose you want to validate so that a phrase starts with "string" and ends with "bee", but does not contain "like". You could use this regular expression (which uses a negative lookahead):
(?!.*like)^sting.*bee$

The negative look ahead will ensure that the expression will not match if the phrase contains "like". For example, "sting as if a bee" would be a match, but "sting like a bee" would not match (because it contains "like"). Now, if you want to disallow both "like" and "as if", the modification is simple:
(?!.*(like|as if))^sting.*bee$

Now neither of the sample phrases I gave above will match.
 
Share this answer
 
Comments
FrewCen 21-Jun-12 14:03pm    
This is that what I wanted to know! Thank you!
Clifford Nelson 21-Jun-12 15:21pm    
Great thing to know, thanks.
The simplest solution would probably be to write a regex to match strings with those words, then throw out the string it if matches.

Something like:
^(words|you|do|not|want|at|start)\b.*\b(words|you|do|not|want|at|end)$
 
Share this answer
 
Comments
FrewCen 21-Jun-12 13:54pm    
Thats not what I wanted. I want to have fixed starting words as 'start' and 'end', but I want text which cannot contain some words, because than it cannot be matched.... Sorry for bit unclear question....
lewax00 21-Jun-12 14:02pm    
Then is "^start.*\b(words|you|do|not|want)\b.*end$" more like it? (Not the most straight forward method, you'd want the strings that don't match instead of the ones that do.)
Maciej Los 21-Jun-12 14:16pm    
It should works! My 5.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900