dr85
dr85

Reputation: 743

Check if word contains substring in Java Regex

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.

Upvotes: 30

Views: 147502

Answers (3)

Andreas Dolk
Andreas Dolk

Reputation: 114767

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.

Upvotes: 61

biziclop
biziclop

Reputation: 49744

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.

Upvotes: 0

Brian
Brian

Reputation: 6450

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

Upvotes: 10

Related Questions