30

If I want to check all words that contain the substring DEF, would this be the right approach:

^.*[D][E][F].*$

Also is there an easy rule when negating regexes, i.e. modifying the above to identify strings that don't contain DEF

EDIT: I know this doesn't require regexes, but for my purposes it does.

3 Answers 3

61

This works too:

^.*DEF.*$

It checks, if the whole String contains the substring "DEF" at least once. But for trivial expressions like this:

str.contains("DEF");

does the same.

1
  • 1
    @LouisRhys, ^ and $ stand for the beginning and end of the string, respectively. If you are using java's String.matches(String), you don't need to use them though, since this method returns true only if the regular expression matches the entire input string. Jun 9, 2013 at 13:29
10

Why not just use str.contains("DEF") and !str.contains("DEF")?

3
  • The built in contains() method just looks along the bytes in the string for an occurrence of chars D, E and F in that order, you could consider it a brute force search. E.g. a string of 100 chars would be "checked" up to ~97 times for that sequence. Regular expressions are a very, very different animal.
    – Brian
    Jan 18, 2011 at 12:49
  • Learn more about string searching/matching at: en.wikipedia.org/wiki/String_searching_algorithm
    – Brian
    Jan 18, 2011 at 12:51
  • 3
    "Why not just use..." because I have to use a regex in my situation. As for answering the question, this might be a better answer for a lot of situations, but you asked "Why not" so here is why not...
    – BillyNair
    Dec 4, 2015 at 19:38
0

You can simply use DEF as your regexp. To identify strings that don't contain it, simply return the strings that don't match the above expression.

3
  • how would you identify using regex all words not containing a particular substring
    – dr85
    Jan 18, 2011 at 14:50
  • Like I said, I'd just negate the result, so it would be !string.matches( "DEF" );
    – biziclop
    Jan 18, 2011 at 15:03
  • but i mean outside of java using just purely a regex
    – dr85
    Jan 18, 2011 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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