ps0604
ps0604

Reputation: 1071

Java regular expression truncates string

I have the following Java string replaceAll function with a regular expression that replaces with zero variables with format ${var}:

String s = "( 200828.22 +400000.00 ) /  ( 2.00 + ${16!*!8!1} ) + 200828.22 + ${16!*!8!0}";
s = s.replaceAll("\\$\\{.*\\}", "0");

The problem is that the resulting string s is:

"( 200828.22 +400000.00 ) /  ( 2.00 + 0"

What's wrong with this code?

Upvotes: 1

Views: 80

Answers (1)

Maroun
Maroun

Reputation: 95998

Change your regex to

\\$\\{.*?\\}
        ↑

* is greedy, the engine repeats it as many times as it can, so it matches {, then match everything until last token. It then begins to backtrack until it matches the last character before }.

For example, if you have the regex

\\{.*\\} 

and the string

"{this is} a {test} string" 

it'll match as follows:

  • { matches the first {
  • .* matches everything until g token
  • the regex fails to match last } in the string
  • it backtracks until it reaches t, then it can match the next } resulting with matching "{this is} a {test}"

In order to make it ungreedy, you should add an ?. By doing that, it'll become lazy and stops until first } is encountered.

As mentioned in the comments, an alternative would be [^}]*. It matches anything that's not } (since it's placed in a character class).

Upvotes: 5

Related Questions