How to Insert Commas Into a Number WITHIN a String of Other Words
题
I have a String
like the following:
"The answer is 1000"
I want to insert commas into the number 1000 without destroying the rest of the String
.
NOTE: I also want to use this for other String
s of differing lengths, so substring(int index)
would not be advised for getting the number.
The best way that I can think of is to use a regex
command, but I have no idea how.
Thanks in advance!
解决方案
The following formats all the non-decimal numbers:
public String formatNumbers(String input) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
NumberFormat nf = NumberFormat.getInstance();
StringBuffer sb = new StringBuffer();
while(m.find()) {
String g = m.group();
m.appendReplacement(sb, nf.format(Double.parseDouble(g)));
}
return m.appendTail(sb).toString();
}
e.g. if you call: formatNumbers("The answer is 1000 1000000")
Result is: "The answer is 1,000 1,000,000"
See: NumberFormat
and Matcher.appendReplacement()
.
其他提示
modified from Most efficient way to extract all the (natural) numbers from a string:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
private static final String REGEX = "\\d+";
public static void main(String[] args) {
String input = "dog dog 1342 dog doggie 2321 dogg";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(input); // get a matcher object
int end = 0;
String result = "";
while (m.find()) {
result = result + input.substring(end, m.start());
result = result
+ addCommas(
input.substring(
m.start(), m.end()));
end = m.end();
}
System.out.println(result);
}
private static String addCommas(String s) {
char[] c = s.toCharArray();
String result = "";
for (int i = 0; i < s.length(); i++) {
if (s.length() % 3 == i % 3)
result += ",";
result += c[i];
}
return result;
}
}
You could use the regular expression:
[0-9]+
To find contiguous sets of digits, so it would match 1000
, or 7500
or 22387234
, etc.. You can test this on http://regexpal.com/ This doesn't handle the case of numbers that involve decimal points, BTW.
This isn't a complete, with code answer, but the basic algorithm is as follows:
- You use that pattern to find the index(es) of the match(es) within the string (the index of the characters where the various matches start)
- From each of those indexes, you copy the digits into a temporary string that contains only the digits of the number(s) in the String
- You write a function that starts at the end of the String, and for every 3rd digit (from the end) you insert a comma before it, unless the index of the current character is
0
(which will prevent300
from being turned into,300
- Replace the original number in the source string with the comma'ed String, using the replace() method