597

I am storing a SQL query in my strings.xml file and I want to use String.Format to build the final string in code. The SELECT statement uses a like, something like this:

SELECT Field1, Field2 FROM mytable WHERE Field1 LIKE '%something%'

In order to format that I replace 'something' with %1$s so it becomes:

SELECT Field1, Field2 FROM mytable WHERE Field1 LIKE \'%%1$s%\'

I escape the single quotes with the backslash. However I am not able to escape the % sign.

How can I include a like statement in my strings.xml file?

5
  • Don't forget to escape the %s properly. Commented Feb 16, 2011 at 2:45
  • 38
    SQL injection alert. Prepare yourself. Commented Feb 16, 2011 at 2:45
  • They'd be injecting into their own database, no concern here ;) Commented Feb 16, 2011 at 3:06
  • 9
    Well, even if it is Your own database, it is possible to accidentally write queries that do bad things. Or just write queries that do not compile. Preparing queries is a good habit to get into. Commented Nov 28, 2014 at 9:16
  • Although it's slower than String.format() you might consider using MessageFormat() instead. Commented May 17, 2018 at 9:53

3 Answers 3

1218

To escape %, you will need to double it up: %%.

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

Comments

32

To complement the previous stated solution, use:

str = str.replace("%", "%%");

2 Comments

This will replace % that are already doubled. Please read the other answer.
@Toilal Why would anyone escape something that is already escaped? And if he would, why not actually do it? Maybe he intended to have two % signs, so the correct escaped form would be '%%%%'
5

This is a stronger regex replace that won't replace %% that are already doubled in the input.

str = str.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");

1 Comment

seems to be an error with the regex: "76%".replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%") gives "7%%"

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.