我想建立一个模式来将逗号插入整数以使其看起来不错,就像1234556
,在操作之后,它会像1,234,556
,所以我使用以下代码:
public static void insertCommaFormly(int n)
{
String input = String.valueOf(n);
String regex = "(?<=\\d)(?=(?:\\d{3},?)+$)";
/*or we can use negative look-around*/
regex = "(?<=\\d)(?=\\d{3}++\\b)";
String replacement = ",";
StringBuffer buffer = new StringBuffer();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
logger.info("Target string is :" + input );
logger.info("Use regex :" + regex);
while(matcher.find())
{
matcher.appendReplacement(buffer, replacement);
logger.info(String.format("Part : '%s'", buffer));
}
matcher.appendTail(buffer);
logger.info("After replace , the string is like : " + buffer.toString());
}
但是,它给了我一个错误(I don't know the reason!
):
Dangling meta character '+' near index 16
(?<=\d)(?=\d{2}++\b)
^
但是如果我使用(?<=\\d)(?=\\d{3}+\\b)
,编译器不会给我抱怨,但是,它会给我错误的结果1234,556
(I don't know why results in this ?
),如果我使用(?<=\\d)(?=(?:\\d{3})+\\b)
,那将是正确的结果。
So here are my two questions , please help me with these , thanks in advance!