Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# string Text RegEx strings
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 21-Jun-12 8:07am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  
Comments
FrewCen at 21-Jun-12 14:03pm
   
This is that what I wanted to know! Thank you!
Clifford Nelson at 21-Jun-12 15:21pm
   
Great thing to know, thanks.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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)$
  Permalink  
Comments
FrewCen at 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 at 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.)
losmac at 21-Jun-12 14:16pm
   
It should works! My 5.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

  Permalink  
v2

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



Advertise | Privacy | Mobile
Web04 | 2.8.1411022.1 | Last Updated 21 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100