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?");}
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.
The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
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).
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With