你如何在java正则表达式中逃避美元和大括号(即$ {title})? [英] How do you escape dollar and braces, (i.e. ${title}) in a java regular expression?

查看:107
本文介绍了你如何在java正则表达式中逃避美元和大括号(即$ {title})?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即如何做到这一点?

String string = "Sample string with ${title} to be inserted.";
string.replaceAll("${title}", title);

以下所有结果均出现错误:

All of the following results in an error:

string.replaceAll("\\${title}", title);
string.replaceAll("\\\\${title}", title);
string.replaceAll("\\\\$\\{title\\}", title);

而且,似乎没有任何效果,这一切都会导致如下错误:

And more, nothing seems to work, it all results in an error like this:

java.util.regex.PatternSyntaxException: Illegal repetition near index 4 \\$\\{title\\}
    at java.util.regex.Pattern.error(Pattern.java:1713)
    at java.util.regex.Pattern.closure(Pattern.java:2775)
    at java.util.regex.Pattern.sequence(Pattern.java:1889)
    at java.util.regex.Pattern.expr(Pattern.java:1752)


推荐答案

不确定最后一个会导致错误;它只是不匹配任何东西,因为你在 $ 上使用了太多的反斜杠。

Not sure how the last one would result in an error; it'd just not match anything because you're using too many backslashes on the $.

这应该有效:

string.replaceAll("\\$\\{title\\}", title);

这篇关于你如何在java正则表达式中逃避美元和大括号(即$ {title})?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆