• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regular Expressions: A String should not contain the word "TEST"  RSS feed

 
Peter Heide
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following regular expression matches for all Strings that contains word TEST, not matter if in the beginning or in the end:

.*TEST.*

How would the regular expression look like that matches for all Strings that do not contain the word TEST?

For testing I am using the following code:



I know that it is possible to program this with the indexOf method of the String class, but I need to implement this using regular expressions.
 
Info Wwn
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, wrong info
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's wrong with the code you have ? If matcher.matches() returns false, the string doesn't contain TEST.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
don't employ the heavy regex engine when an indexOf just does fine ...
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You must use negative lookahead construct:
This will match only if string doesn't contain TEST:

 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why simple when you can do it incredibly complicated :-)

how about

 
Peter Heide
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for all your help guys! Of course you are right, the simplest code ist the best for the given problem.
But I wanted to figure out how to solve it with an regular expression. Thank you Ireneusz Kordal for your correct regular expression!

The following code :


Delivers the following answer I needed:

This program delivers false when a String contains the String "TEST" and true otherwise (It is forbidden to have the Substring "TEST" in a String)
OK! String "TEST" delivers false
OK! String "TEST TEST" delivers false
OK! String "123 TEST 456" delivers false
OK! String "Peter" delivers true

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
matches() only returns true if the entire String matches the entire regex. Use find() otherwise.

You may also want to check out the Pattern.CASE_INSENSITIVE flag, that way you don't need to use toUpperCase().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!