user2698684
user2698684

Reputation: 131

Search and replace with regular expressions in Java

In my string, I want to put a # in start and end of : cast(.* as varchar)

I tried:

s.replaceAll("cast(.* as varchar)","#cast$1#");

But for a string "('abas' + cast(x as varchar ))" the result is "( ' abas ' +' # cast ( x as varchar # ' ) )" which is not correct. What am I doing wrong?

Upvotes: 0

Views: 59

Answers (2)

Wilder Pereira
Wilder Pereira

Reputation: 2267

s.replaceAll("(cast\\(\\.\\* as varchar\\))","#$1#");

Will do the trick.

You were getting the wrong output because the parenthesis around ".* as varchar" weren't being scaped so the $1 was replacing what was inside them.

Upvotes: 2

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18825

() have special meening, you need to escape:

s.replaceAll("(cast\\(.* as varchar\\))","#$1#");

Upvotes: 0

Related Questions