Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java regex?

 
Sloan Bowman
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sloan Bowman
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic