Explain Codes LogoExplain Codes Logo

How to use regex in String.contains() method in Java

java
regex
string-methods
pattern-quote
Alex KataevbyAlex Kataev·Jan 6, 2025
TLDR
// Ahh, regex. Lookin' scary, but actually a cuddly teddy bear 🐻 String text = "Hello, StackOverflow!"; String regex = ".*StackOverflow.*"; // We are hunting for StackOverflow. Oh my, this feels like The Matrix! // Invoking the mighty combo of Pattern and Matcher, as String.contains() can't chew on regex! boolean contains = Pattern.compile(regex).matcher(text).find(); // Now let's jazz it up in a function boolean containsRegex(String str, String pattern) { return Pattern.compile(pattern).matcher(str).find(); } boolean result = containsRegex(text, regex); // Voila! The Matrix is alive!

Here, Pattern.compile() generates a Pattern object, matcher() spawns a Matcher against the input text, and finally find() checks for a match. The containsRegex utility function wraps all this jazz in a neat little package.

Strumming with String.matches()

Remember .contains()? It's great for a one-on-one matchup — exact words — but it wrestles with regex. Here's why:

String safeString = "123 safe"; boolean safe = safeString.contains("\\d+"); // Yikes! Returns false.

In the ring steps String.matches(). But beware, it's a tough cookie—it demands a match of the entire string, not just a bit or byte.

Takeaway: For partial matches, let Matcher.find() take the ring.

Handling Special Characters

Special characters can come with a special headache. Not to worry—Pattern.quote() to the rescue! It expertly handles those pesky special characters in regex patterns:

String shiftyString = "10$bill"; // Special `.` and `$` characters lurking String safeRegex = "\\b" + Pattern.quote(shiftyString) + "\\b"; boolean safe = containsRegex(safeString, safeRegex); // Safe and sound

Remember: When uncertainty beckons, Pattern.quote() is the hero you need.

The Mighty Word Boundaries

Matching whole words and not mere substrings is where \\b enters the scene. A pattern like "\\bcat\\b" will match "wild cat" but not "caterpillar".

Lesson in Efficiency

If your readers, uh, I mean code, will use the same pattern frequently, it’s more efficient to compile the pattern once:

Pattern repeatOffenderPattern = Pattern.compile("repeatOffender"); // Just reuse your Pattern object with different strings. Adulting done right!

Error Handling

In the rough world of code, a PatternSyntaxException can pop up when you least expect it. Fortify your code with a try-catch block:

try { Pattern dangerousPattern = Pattern.compile("some(?:dangerousPattern"); } catch (PatternSyntaxException pse) { // Handle it gracefully, maybe with a `printf("Ouch, that hurt!")`. }

Knowing Your find() from matches()

Use Matcher.matches() to verify if the entire string adheres to the pattern. For partial matches, make Matcher.find() your new best friend.

Wrangling Multilines

Taming multi-line strings? Use the handy . matches with a dot-all flag (?s), allowing . to match new line characters:

String multiLineDoc = "First line.\nSecond line.\nThird line."; boolean multilineMatch = containsRegex(multiLineDoc, "(?s)First.*Third"); //Bam! Regex nailed it!

Tech Ninja Skills with Pattern and Matcher

Here's how you can maximize these beauties for various tasks:

Search for Patterns

Matcher m = pattern.matcher(text); while (m.find()) { System.out.println("Found ya at: " + m.start() + " Playing hide and seek, were we?"); }

Replace All of Them

String newTex = m.replaceAll("newKidOnTheBlock"); // The old is gone, the new has arrived!

Group Extraction

if (m.find()) { String group = m.group(1); // Love playing with groups. More the merrier! }