Preventing % to %20 in replaceAll - java

I'm trying to format a string in a Java Servlet to add to a JDBC SELECT query. I need to replace %20's with a % for my LIKE conditional.
nameQuery.replaceAll("%20", "%");
String query = String.format("SELECT name, imageURL FROM User " +
"WHERE name LIKE \'%%%s%%\' AND userID != %d", nameQuery, userId);
With this code, all the %20 still don't get replaced. For a nameQuery value like "Allison%20s", calling nameQuery.replaceAll("%20", "%") changes it to "Allison%20s" (no change). Even escaping the % doesn't fix this. How can I make replaceAll convert the % to a %20?

It seems like what you've actually got is a string containing %20 and you want to replace it with something else. You can do that with replace
nameQuery = nameQuery.replace("%20", "%"); // replace %20 with a %
You could also have used replaceAll, but you don't appear to be capturing the return value of replaceAll; just calling it and ignoring the result.

Related

How to replace single quote within a string with two single quotes in java?

I have the below data in my text file.
1|"John"|3,5400
2|"Jim"|7,7300
3|"Smith,Robin",3,4300
4|"O'Brien",10,8200
and I want this output:
(1,'John',3,5400)
(2,'Jim',7,7300)
(3,'Smith,Robin',3,4300)
(4,'O''Brien',10,8200)
Basically I want to replace | character with commas and double quotes with single quote. I am able to achieve that with this piece of code:
String text2 = textAfterHeader.replaceAll("\\|", ",").replaceAll("\"", "'").replaceAll("[a-zA-Z]'[a-zA-Z]", "''");
output that I am getting:
1,'John',3,5400
2,'Jim',7,7300
3,'Smith,Robin',3,4300
4,'''rien',10,8200
But I have one more requirement where I need to put two single quotes whenever a single quote appears between a string, for example, O'Brien as O''Brien. But this part is not working.
As was suggested by #AndyTurner, you can simplify the problem by first replacing all ' with '' and then replace all " with '. The only thing missing after that are the parenthesis, which can be added in two steps:
Replace all blanks with ) ( (notice the blank between the parenthesis).
Add a leading ( and a trailing ) to the String.
All together, a solution could look like this:
final String output = "("
+ input
.replace("'", "''")
.replace("\"", "'")
.replace("|", ",")
.replace(" ", ") (")
+ ")";
Ideone demo
Try this regex:
\s*\'\s*
and a call to Replace with " will do the job.
A possible solution could be:
String lineSeparator = System.getProperty("line.separator");
String output = new StringBuilder("(").append(
input.replaceAll("\\|", ",")
.replaceAll("'", "''") // (*)
.replaceAll("\"", "'") // (**)
.replaceAll(lineSeparator, ")" + lineSeparator + "("))
.append(")").toString();
Note the replacement (*) must come before (**). Since you need to replace exact characters instead of variable regular expressions, you want better use replace instead of replaceAll.

Spring REST #Query variable parameters

I'm currently building a REST API in spring, and would like to add a search method which takes in a list of letters and search for sequences based on those letters. The code I have below is an example of what i've achieved so far. It does the job, and searches based on the letter parameters. But it's limited to have to use exactly the number of params specified in the method.
#Query("SELECT f FROM Item f " +
"WHERE LOWER(f.title) LIKE CONCAT(" +
" '%',LOWER(:letter1)," +
" '%',LOWER(:letter2)," +
" '%',LOWER(:letter3)," +
" '%',LOWER(:letter4),'%')")
#RestResource(rel = "title-fragmented", path="findByFragments")
Page<Item> findByFragmented(#Param("letter1") String letter1,
#Param("letter2") String letter2,
#Param("letter3") String letter3,
#Param("letter4") String letter4,
Pageable page
);
I was wondering if it is possible to achieve the same result without specifying the number of letters to be concatenated. So for example when
/api/v1/search/findByfragments?letter=A&letter=B&letter=C....
is called, it'll work. I've tried passing string arrays as a the #Param value, but couldn't get it to work.
Thanks in advance.
Solved my issue by using SpEL expressions to split apart a single string, and replace the letters between them with wildcard(%) expression. Example below for anyone who may find themselves with the same issue:
#Query(
"SELECT f FROM Item f WHERE LOWER(f.title) LIKE CONCAT('%',LOWER(:#{#title.replaceAll('','%')}),'%')"
)
#RestResource(rel = "item-title-by-fragments", path="fragments")
Page<Item> findUsingFragments(#Param("title") String title, Pageable page);

Regular expression pattern to find a number within a semicolon delimited list of numbers

String temp = "77"; // It can be 0 or 100 or any value
// So the pattern will be like this only but number can be change anytime
String inclusion = "100;0;77;200;....;90";
I need to write a regular expression so that I can see whether temp exists in inclusion or not so for that I wrote a regexPattern like this.
// This is the regular Expression I wrote.
String regexPattern = "(^|.*;)" + temp + "(;.*|$)";
So do you think this regular expression will work everytime or there is some problem with that regexPattern?
if(inclusion.matches(regexPattern)) {
}
You could run into issues if temp can contain special characters for regular expressions, but if it is always integers then your method should be fine.
However, a more straightforward way to do this would be to split your string on semi-colons and then see if temp is in the resulting array.
If you do stick with regex, you can simplify it a bit by dropping the .*, the following will work the same way as your current regex:
"(^|;)" + temp + "(;|$)"
edit: Oops, the above will actually not work, I am a bit unfamiliar with regex in Java and didn't realize that the entire string needs to match, thanks Affe!
You don't need regex:
temp = "77"
String searchPattern = ";" + temp + ";";
String inclusion = ";" + "100;0;77;200;....;90" + ";";
inclusion.indexOf(searchPattern);
Another alternative without regex
String inclusion2 = ";" + inclusion + ";"; // To ensure that all number are between semicolons
if (inclusion2.indexOf(";" + temp + ";") =! -1) {
// found
}
Of course, no pattern recognition here (wildcards and the like)

How to remove the degrees celsius symbol from a string (java)

I've been trying to remove the degree Celsius symbol from the following string for a few hours now. I've looked at prior posts and I see that /u2103 is the unicode representation for it. Despite trying to remove that string, I've still had no luck. Here's what I have now:
String temp = "Technology=Li-poly;Temperature=23.0 <degree symbol>C;Voltage=3835";
StringBuilder filtered = new StringBuilder(temp.length());
for (int i = 0; i < temp.length(); i++) {
char test = temp.charAt(i);
if (test >= 0x20 && test <= 0x7e) {
filtered.append(test);
}
}
temp = filtered.toString();
temp.replaceAll(" ", "%20");
The resulting string looks like this:
Technology=Li-poly;Temperature=23.0 C;
I've also tried
temp.replaceAll("\\u2103", "");
temp.replaceChar((char)0x2103, ' ');
But none of this works.
My current problem is that the function to filter the string leaves a blank space but the call to replaceAll(" ", "%20") doesn't seem to recognize that particular space. ReplaceAll will replace other spaces with %20.
This is one problem:
temp.replaceAll(" ", "%20");
You're calling replaceAll but never using the result. Strings are immutable - any method which looks like it's changing the content is actually returning the different string as a result. You want:
temp = temp.replaceAll(" ", "%20");
Having said that, it's not clear why you're trying to replace the space at all, nor what's wrong with your resulting string.
You've got the same problem with your other temp.replaceAll and temp.replaceChar calls.
Your attempt to replace the character directly would also fail as you're escaping the backslash - you really want:
temp = temp.replace("\u2103", "");
Note the use of replace instead of replaceAll - the latter uses regular expressions, which there's no need to use at all here.
Perhaps you could leverage the Character.isWhiteSpace() function.

SQL Query passing values from Java

I would like to know if when I place a sql query using java , does it retain the new lines?
for instance if i have
"IF EXISTS (SELECT * FROM mytable WHERE EMPLOYEEID='"+EMPID+"')"+
"UPDATE myTable SET ....)"
So after the "+" sign in the first line the UPDATE follows, does it maintain the new line when it is being passed to the database?
Thank you
No. For the query to work successfully you will have to add a space before UPDATE or after ).
Firstly, there is no newline in the example source code to "maintain" ...
Secondly, your problem is with Java rather than SQL. You will only get an newline into a Java String if you put it there explicitly; e.g.
// No newline in this string
String s = "a" +
"b";
// Line break in these strings
String s = "a" + "\n" + "b";
String s2 = "a\nb";
String s3 = "a" + System.getProperty("line.separator") + "b";
Finally, in your example, a space or TAB will do just as well as a line break.

Categories

Resources