Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern.matches doesn't work, while replaceAll does

Tags:

java

regex

The regular expression seems to be ok, since the first line line correctly replace the substring with "helloworld", but the same expression won't match in the latter since i cannot see "whynothelloworld?" on console

System.out.println(current_tag.replaceAll("^[01][r]\\s", "helloworld"));

if (Pattern.matches("^[01][r]\\s", current_tag)) { System.out.println("whynothelloworld?");}
like image 548
Gabriele B Avatar asked Jun 29 '11 14:06

Gabriele B


People also ask

Does replaceAll use regex?

The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.

What do the replaceAll () do in Java?

The replaceAll() method replaces each substring that matches the regex of the string with the specified text.

Does the pattern match the string Java?

Java - String matches() MethodThis method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).

How does pattern and matcher work in Java?

Matcher pattern() method in Java with ExamplesThe pattern() method of Matcher Class is used to get the pattern to be matched by this matcher. Parameters: This method do not accepts any parameter. Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher.


1 Answers

Pattern.matches() expects the entire string to match, not just a substring.

Use the .find() method of the regex matcher object instead:

Pattern regex = Pattern.compile("^[01]r\\s");
Matcher regexMatcher = regex.matcher(current_tag);
foundMatch = regexMatcher.find();
like image 87
Tim Pietzcker Avatar answered Sep 17 '22 18:09

Tim Pietzcker