问题描述
我正在尝试编写一个接受 String
的方法,检查某些令牌的实例(例如 $ {fizz} code>,
$ {buzz}
, $ {foo}
等),并将每个令牌替换为一个新的字符串,从 Map< String,String>
中获取。
I am trying to write a method that will accept a String
, inspect it for instances of certain tokens (e.g. ${fizz}
, ${buzz}
, ${foo}
, etc.) and replace each token with a new string that is fetched from a Map<String,String>
.
例如,如果我通过方法以下字符串:
For example, if I pass this method the following string:
如果该方法查询了以下 Map< String,String>
:
And if the method consulted the following Map<String,String>
:
Key Value
==========================
"fizz" "brown"
"buzz" "arsonist"
"foo" "feet"
然后结果字符串将是:
这是我的方法:
String substituteAllTokens(Map<String,String> tokensMap, String toInspect) {
String regex = "\\$\\{([^}]*)\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(toInspect);
while(matcher.find()) {
String token = matcher.group(); // Ex: ${fizz}
String tokenKey = matcher.group(1); // Ex: fizz
String replacementValue = null;
if(tokensMap.containsKey(tokenKey))
replacementValue = tokensMap.get(tokenKey);
else
throw new RuntimeException("String contained an unsupported token.");
toInspect = toInspect.replaceFirst(token, replacementValue);
}
return toInspect;
}
当我运行这个,我得到以下异常:
When I run this, I get the following exception:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 0
${fizz}
^
at java.util.regex.Pattern.error(Pattern.java:1730)
at java.util.regex.Pattern.closure(Pattern.java:2792)
at java.util.regex.Pattern.sequence(Pattern.java:1906)
at java.util.regex.Pattern.expr(Pattern.java:1769)
at java.util.regex.Pattern.compile(Pattern.java:1477)
at java.util.regex.Pattern.<init>(Pattern.java:1150)
at java.util.regex.Pattern.compile(Pattern.java:840)
at java.lang.String.replaceFirst(String.java:2158)
...rest of stack trace omitted for brevity (but available upon request!)
为什么我得到这个?
Why am I getting this? And what is the correct fix? Thanks in advance!
推荐答案
在 $ {fizz }
{
是正在启动的正则表达式引擎的指标重复指示符,如 {2,4}
,这意味着前一个令牌的2到4倍。但是, {f
是非法的,因为它必须跟随一个数字,所以它会抛出一个例外。
{
is an indicator to the regex engine that you are about to start a repetition indicator, like {2,4}
which means '2 to 4 times of the previous token'. But {f
is illegal, because it has to be followed by a number, so it throws an exception.
您需要逃避所有正则表达式元字符(在这种情况下 $
, {
和}
)(尝试使用)或使用不同的替代方法字符串的字符串,而不是字符串的正则表达式。
You need to escape all regex metacharacters (in this case $
, {
and }
) (try using http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#quote(java.lang.String) ) or use a different method that substitutes a string for a string, not a regex for a string.
这篇关于Java PatternSyntaxException:字符串替换的非法重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!