Search code examples
javaregexreplaceall

Using Java's replaceAll to replace the whole string


I am trying to use following code to replace the whole string:

Code: String a = "Hello"; String b = a.replaceAll("(?s).*", "US"); Output:

USUS

Question: Why is the string "US" repeated twice? How can I replace the whole string using replaceAll function, making use of regular expression?

Why I need to do this: I need to pick up replace patterns specified in a json file with the values given there. In this model, I wanted to give independence to the user(json configurer) to define a pattern such that entire string may be replaced, without me having to code special handling of string replacement.


Solution

  • It's because .* can match an empty string. so the first match is all the string (from the begining) and the second is the empty string (from the last position of the string after the last character)

    You can avoid this behaviour using the + quantifier instead of *. But it will not replace an empty string.