Reputation: 7074
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!
Upvotes: 2
Views: 4736
Reputation: 51030
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()
.
Upvotes: 5
Reputation: 7910
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;
}
}
Upvotes: 1
Reputation: 33954
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:
0
(which will prevent 300
from being turned into ,300
Upvotes: 0