Prev Next

Java / Regular expressions

Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. What is the difference between matches() and find() in Java Regex?

matches() matches the expression against the entire string as it implicitly add a ^ at the start and $ at the end of your pattern, so it will not match substring or part of the string. ^ and $ are meta characters that represents start of the string and end of the string respectively.

find() matches the next occurrence within the substring that matches the regex.

public class PatternMatchExample {

	public static void main(String[] args) {
		Pattern p = Pattern.compile("[a-zA-Z]{9}");
		Matcher m = p.matcher("www.javapedia.net");
		System.out.println("Javapedia matched :" + m.matches());
		System.out.println("Javapedia found :" + m.find());
	}
}

2. Explain the difference between String.matches and Matcher.matches.

Matcher.matches() is good in terms of performance as a Matcher is created on a precompiled regular expressions, while the String.matches() recompiles the regular expression every time it executes.

3. Is Java Regex Thread Safe?

Instances of Pattern class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not thread safe.

«
»
Design Patterns

Comments & Discussions