开发者

Check if word contains substring in Java Regex

开发者 https://www.devze.com 2023-02-05 20:32 出处:网络
If I want to check all words that contain the substring DEF, would this be the right approach: ^.*[D][E][F].*$

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 pu开发者_StackOverflowrposes it does.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消