This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I am wanting to write a method that replaces bad characters with html entities in xml documents. I have tried to create an array with entities and an array with the characters that match and use the String.replaceAll(String match, String replace) method of the String class within in for loop but don't get the results I exspected. Any ideas on how to write a very simple method to do this. My Example: public String makeClean(String aString) { String[] values = new String[] { "\"", "'" };
String[] entities = new String[] { ""e;", "’" }; for (int i=0; i < values.length; i++) { aString.replaceAll(values[i], entities[i]); } return(aString); }
Hi Sloan Try, aString = aString.replaceAll(values[i],entities[i]); in the for loop you have because replaceAll() returns the new String. Please note that String is a immutable object in Java so it can't replace String value "inline" as you seem to expecting it... Regards Maulin
I appreciate the response. I realize that String objects are immutable so would I be better off using a StringBuffer? If so how could I go about doing so. Thanks for your previous help.
Sloan Bowman
Ranch Hand
Joined: Jan 21, 2003
Posts: 107
posted
0
I have now learned how to use java.util.regex package but still need to know how to check againse multiple instances of different values without using multiple methods calls. For example to search and replace quotes, right quotes, and apostrophes all in one method call and return the result as a string. Here is an example of my regex code.
Example: import java.util.regex.*; public class RegExtTest { // Start main class public static void main(String[] args) { if (args.length != 2) { System.out.println("java RegExTest regex text"); return; } String rString = makeClean(args[0], args[1]); System.out.println(rString); } // end main public static String makeClean(String pattern, String text) { StringBuffer sb = new StringBuffer(); try { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(text); while(m.find()) { m.appendReplacement(sb, ""e;"); } m.appendTail(sb); } catch (Exception e) { System.out.println(e.getMessage()); } return(sb.toString()); }
} // end class
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.