0

i have a java code where i select a record from db using Spring Hibernate native query and tried to strip HTML tags from a text.

  String sql = " SELECT * FROM posts LIMIT 1 ";
  SQLQuery query = getSession().createSQLQuery(sql);
  query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  Map each = (Map)query.uniqueResult();     
  String message = (String)each.get("Message");
  String content = message.replaceAll("\\<.*?\\>", "");

But why replaceAll does not work here ?

But for this code it works:

  String message = "<a>blablasdddfdf</a>";
  String content = message.replaceAll("\\<.*?\\>", "");

Thanks.

taras
  • 2,223
  • 5
  • 36
  • 43

1 Answers1

2

Both of your cases shouldn't work. In second case:

String message = "<a>blablasdddfdf</a>";
String content = content.replaceAll("\\<.*?\\>", "");

what would replaceAll method would replace in content when content hasn't been assigned any initial value?

Your last line should be:

 String content = message.replaceAll("\\<.*?\\>", "");

in both of the cases to work properly.

In first case, just make sure that you have some value in message before invoking replaceAll on it.

craftsman
  • 15,133
  • 17
  • 70
  • 86
  • in first code, message has a value, its converted from Object to String. i wonder String.replaceAll() does not work for Cast strings ? – taras Apr 06 '11 at 14:26
  • Casting doesn't matter. As long as JVM is allowing your object to be casted to String, you can invoke replaceAll() on it. May be you need to check the value of message before you invoke replaceAll() on it. It might be containing an empty string or some other unexpected thing. – craftsman Apr 06 '11 at 16:42
  • it contains value, its correct String. i tried to output that value, and copy it and assign the value to string variable: String value = "sdsdsdsd

    "; then used value.replaceAll() and it works. its not working if i read the value from db query result and use replaceAll.
    – taras Apr 07 '11 at 02:12