Forums Register Login

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

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Oops, wrong info
+Pie Number of slices to send: Send
What's wrong with the code you have ? If matcher.matches() returns false, the string doesn't contain TEST.
+Pie Number of slices to send: Send
don't employ the heavy regex engine when an indexOf just does fine ...
+Pie Number of slices to send: Send
You must use negative lookahead construct:
This will match only if string doesn't contain TEST:

+Pie Number of slices to send: Send
Why simple when you can do it incredibly complicated :-)

how about

+Pie Number of slices to send: Send
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

+Pie Number of slices to send: Send
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().
"To do good, you actually have to do something." -- Yvon Chouinard
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 23302 times.
Similar Threads
Regular Expression pattern search is throwing "java.lang.IllegalStateException"
How to use OR in Regular Expressions?
Counting exact matches of substring.
search string from bigger string
SPLIT METHOD IN STRING CLASS
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:36:05.