Reputation: 11
I've seen other people ask similar questions to this before and have followed the instructions given to those people, but I still cannot get my code to function correctly.
try {
FileReader fr_p = new FileReader("p.txt");
BufferedReader in_p = new BufferedReader(fr_p);
String line = in_p.readLine();
for (;;) {
line = line.replaceAll("&","&");
line = line.replaceAll("<","<");
line = line.replaceAll(">",">");
line = line.replaceAll("\"",""");
people.add(line);
line = in_p.readLine();
if (line == null) break;
}
in_p.close();
} catch (FileNotFoundException e) {
System.out.println("File p.txt not found.");
System.exit(0);
} catch (IOException e) {
System.out.println("Error reading from file.");
System.exit(0);
}
This is the code that I've written to attempt to take each name on a separate line of a text file, and put it into an ArrayList, replacing the special characters with their XML entities. I then write this into an HTML file later on.
The code that I've written does this just fine for the first three characters, but when it reaches the line attempting to change any double quotes to "
, it doesn't change them and ends up giving me â€
instead of a double quote. I'm not sure what else I should change about my code to get this to work.
Upvotes: 0
Views: 18838
Reputation: 350
you have an encoding problem, you can resolve that by setting the single quote by its unicode code :
line = line.replaceAll("\"", "\u0027");
Upvotes: 0
Reputation: 1876
I would change your code to something like this
line = line.replace("&","&")
.replace("<","<")
.replace(">",">")
.replace("\"",""");
It should work like yours but there is no need to use regexp for simply replacement.
Upvotes: 1
Reputation: 3736
I got the same behaviour as you. The java compiler is eating your escape character on the quote'"' character. There must be something odd with regex compiler expecting a quote to be escaped as well when fed a string literal. It isn't supposed to, but in this case it is.
If you prepend an escaped escape, it will work.
String lineout = line.replaceAll("\\\"",""e;");
Alternately, you can can use a String object for your search expression.
String line = "embedded\"here";
String searchstring = "\"";
String lineout = line.replaceAll(searchstring,""e;");
Upvotes: 1
Reputation: 533492
When I run
String line = "This is a string with \" and \" in it";
line = line.replaceAll("\"",""");
System.out.println(line);
I get
This is a string with " and " in it
Note: there is lots of different kinds of quotation marks but there is only one "
character. If you have a different quotation mark, it will not match.
https://en.wikipedia.org/wiki/Quotation_mark
Upvotes: 2