How to Replace dot (.) in a string in Java

后端 未结 4 1769
[愿得一人]
[愿得一人] 2020-11-28 12:26

I have a String called persons.name

I want to replace the DOT . with /*/ i.e my output will be persons/*/name

相关标签:
4条回答
  • 2020-11-28 12:54

    If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

    replace replaces each matching substring but does not interpret its argument as a regular expression.

    str = xpath.replace(".", "/*/");
    
    0 讨论(0)
  • 2020-11-28 12:59

    Use Apache Commons Lang:

    String a= "\\*\\";
    str = StringUtils.replace(xpath, ".", a);
    

    or with standalone JDK:

    String a = "\\*\\"; // or: String a = "/*/";
    String replacement = Matcher.quoteReplacement(a);
    String searchString = Pattern.quote(".");
    String str = xpath.replaceAll(searchString, replacement);
    
    0 讨论(0)
  • 2020-11-28 13:04

    You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

    str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/
    

    http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

    0 讨论(0)
  • 2020-11-28 13:17

    return sentence.replaceAll("\s",".");

    0 讨论(0)
提交回复
热议问题