开发者

Matching and replace all occurencies of backslash in a string

开发者 https://www.devze.com 2023-04-11 13:43 出处:网络
I use the following in GWT to find the backslash from a string and replace with \\\\. String name = \"\\path\\item\";

I use the following in GWT to find the backslash from a string and replace with \\.

String name = "\path\item";
name = RegExp.compile("/\\/g").replace(name, "\\\\");

But it does not work, because for name=\path\item returns name=\path\item.

ok i follow the recomendation of Thomas Broyer and the first RegExp.compile("\\", "g").replace(bgPath, "\\\\") gives:

Caused by: com.google.gwt.core.client.JavaScriptException: (SyntaxError): trailing \ in regular expression
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:237)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:132)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
    at com.google.gwt.regexp.shared.RegExp$.compile(RegExp.java)
    at com.ait.gwt.authtool.client.ui.TicketViewer.<init>(TicketViewer.java:197)
    at com.ait.gwt.authtool.client.AuthTool.onViewTicketBtnClicked(AuthTool.java:1942)
    at com.ait.gwt.authtool.client.AuthTool.onMessageReceived(AuthTool.java:1995)
    at com.ait.gwt.authtool.client.events.MessageReceivedEvent.dispatch(MessageReceivedEvent.java:44)
    at com.ait.gwt.authtool.client.events.MessageReceivedEvent.dispatch(MessageReceivedEvent.java:1)
    at com.google.gwt.event.shared.GwtEvent.dispatch(GwtEvent.java:1)
    at com.google.web.bindery.event.shared.SimpleEventBus.doFire(SimpleEventBus.java:193)
    at com.google.web.bindery.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:88)
    at com.google.gwt.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:52)

and the second bgPath.replaceAll("\\", "\\\\") gives:

Caused by: java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 
\ 
 ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.reg开发者_JAVA百科ex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    at com.ait.gwt.authtool.client.ui.TicketViewer.<init>(TicketViewer.java:198)

but when i type: bgPath = bgPath.replaceAll(Pattern.quote("\"), Matcher.quoteReplacement("\\"));

works normally(!!) as it gives: [INFO] [gwt_app] - !!! bgPath=Background\\Cartoon\\image


RegExp.compile is the equivalent to new Regexp in JS, so the argument is not a regexp literal. Your code should read RegExp.compile("\\", "g").

But for this particular case, name.replace("\\", "\\\\") should be enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号