0

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?

1
  • 1
    be more clear. give your exact input and output vs what you would like it to output Commented Oct 29, 2016 at 0:46

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

3 Comments

You also need to escape the '.' and '*' characters.
This time the result is "( ' abas ' +'#cast#' ( x as varchar ) )" which is still not correct
I also tried: s.replaceAll("cast(\(.* as varchar.*\))","#cast$1#")) , but still I get a wron answer: "('abas' + #cast(x as varchar ))#"
0

() have special meening, you need to escape:

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

1 Comment

the result is "( ' abas ' +'#cast#' ( x as varchar ) )" which is still not correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.