JSF: How to replace “\\” in a string

人走茶凉 提交于 2019-12-23 00:45:07

问题


Suppose I have the string text\\, I need to replace \\ with /. I tried the following expression:

/*  str = "text\\"  */
<h:outputText value="#{fn:replace(str, '\\', '/')}" />

But I always run into the following exception:

Caused by: java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Pattern.java:1924)
at java.util.regex.Pattern.compile(Pattern.java:1671)
at java.util.regex.Pattern.<init>(Pattern.java:1337)
at java.util.regex.Pattern.compile(Pattern.java:1022)
at java.lang.String.replaceAll(String.java:2210)
at com.sun.faces.facelets.tag.jstl.fn.JstlFunction.replace(JstlFunction.java:222)

I'd be very grateful if you could give me an advice.

UPDATE: Based on the answers below, I found out that the following expression will work:

<h:outputText value="#{fn:replace(str, '\\\\', '/')}" />

Best regards,


回答1:


Try this (haven't checked....)

<ui:param name="mydouble" value="\\\\"></ui:param>
<ui:param name="mysingle" value="/"></ui:param>
<h:outputText value="#{fn:replace(str, mydouble, mysingle)}" />



回答2:


I believe you need to escape the backslashes. Try this: replace("\\\\", "/")

public class BackSlashEscaper {

    public static void main(String[] args) {

        String text = "text\\\\";
        System.out.println(text);

        System.out.println(text.replace("\\\\", "/"));
    }
}

Output:

text\\
text/



回答3:


Just to demonstrate with one backslash:

public static void main(String[] args)
    {
        String text = "text\\";

        System.out.println(text.replaceAll("\\\\","/"));
    }



回答4:


public class TempClass {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        System.out.println("before : "+str);
        String newstr = str.replace("\\", "/");
        System.out.println("after  : "+newstr);
    }
}

When I provide input as text\\ I get output as text//

before : text\\
after  : text//


来源:https://stackoverflow.com/questions/11492569/jsf-how-to-replace-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!