Search code examples
javajasper-reportsreplaceall

Java .replaceAll() for $ and \


I have use the replaceAll() function in my Java ireport for one of the text field. The following codes need to replace all the matche strings to $ sign or \ character . However, it is only work for replace() function only.

$P{name}.replaceAll('abc', '\$');

or

$P{name}.replaceAll('abc', '\\');

Solution

  • Use double escape character \

    String str = "abc-d-abc";
    str = str.replaceAll("abc", "\\$");
    System.out.println(str);
    
    String str1 = "abc-d-abc";
    str1 = str1.replaceAll("abc", "\\\\");
    System.out.println(str1);
    

    replace: It will replace all occurrence of Character/String matched in String. replace can't process Regular Expression.

    replaceAll: It will replace all occurrence of Character/String matched in String. replaceAll can process Regular Expression. Its slower because it has to process regular expression