[英]Java replace all string, replacing all numbers less than 3
public static enum pie {
APPLE_PIE1(1, 250),
PUMPKIN_PIE1(2, 300),
OTHER_PIE1(3, 350),
APPLE_PIE2(4, 400),
OTHER_PIE2(5, 450),
PUMPKIN_PIE2(6, 500),
APPLE_PIE3(7, 550),
;
private static Map<Integer, pie> pie = new HashMap<Integer, pie>();
static {
for(pie pie : pie.values()) {
pie.put(pie.getId(), pie);
}
}
public static pie forId(int id) {
return pie.get(id);
}
private pie(int id, double exp) {
this.id = id;
this.exp = exp;
}
public int id;
public double exp;
System.out.println("My favorite type of pie is " + pie.toString().toLowerCase().replaceAll("_", " ").replaceAll("2", "").replaceAll("3", "").replaceAll("4", "") + ".");
Example code ripped up, but how would I make that '.replaceAll(" number ", "")' replace all numbers less than or equal to 4 with a more simple code? 示例代码破了,但是我如何用一个更简单的代码使'.replaceAll(“ number ”,“”)'替换所有小于或等于4的数字呢? Creating a new .replaceAll 3 times is redundant. 创建一个新的.replaceAll 3次是多余的。 If I do...: 如果我做...:
double number[] = {1, 2, 3, 4};
pie.toString().toLowerCase().replaceAll("_", " ").replaceAll(number.toString(), "") + ".");
...I'll get a nasty error. ...我会收到一个讨厌的错误。
Here's the error... 这是错误...
SEVERE: An error occurred in an executor service! The server will be halted immediately.
java.util.regex.PatternSyntaxException: Unclosed character class near index 9
[D@12452e8
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.clazz(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
To fix your error, you should just replace 要解决您的错误,您只需更换
double number[] = {1, 2, 3, 4};
by 通过
String number = "[1, 2, 3, 4]";
But I would not use replaceAll to do that. 但是我不会使用replaceAll来做到这一点。 Instead, I would add a label
field to your enum, in a similar way as the other fields, and call getLabel()
instead of toString()
, or override toString()
to return the label: 相反,我将以与其他字段类似的方式向您的枚举添加一个label
字段,并调用getLabel()
而不是toString()
,或重写toString()
以返回标签:
public static enum pie {
APPLE_PIE1(1, 250, "apple pie"),
PUMPKIN_PIE1(2, 300, "pumpkin pie"),
...
private int id;
private double exp;
private String label;
private pie(int id, double exp, String label) {
this.id = id;
this.exp = exp;
this.label = label;
}
public String getLabel() {
return label;
}
// optional: I wouldn't do it as it would make debugging harder
@Override
public String toString() {
return label;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.