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

2019-05-23 03:51发布

问题:

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//