Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if word contains substring in Java Regex

Tags:

java

string

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.

like image 710
dr85 Avatar asked Jan 18 '11 12:01

dr85


People also ask

Can I use regex in contains Java?

String. contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.

How do you check if a string contains a substring in Java?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do I check if a string contains a specific word in Java?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.


1 Answers

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.

like image 61
Andreas Dolk Avatar answered Sep 16 '22 14:09

Andreas Dolk