質問するログイン新規登録

回答編集履歴

2

replaceAll を使うコードを追加

2020/12/23 07:28

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -6,4 +6,26 @@
6
6
 
7
7
  repalceAll を使わずに、
8
8
  `NumberFormat.getNumberInstance().format(Integer.parseInt("1000"))`
9
- のようにもできますが、String.format の方が簡単でしょう。
9
+ のようにもできますが、String.format の方が簡単でしょう。
10
+
11
+ **追記**
12
+ replaceAll を使おうとするのは、数字を含む文字列があって、
13
+ その中の数字の部分だけをコンマ付きにしたいということではないのですか?
14
+
15
+ 次のようにすればできます。
16
+ ```Java
17
+ class Test {
18
+ public static void main(String[] args) {
19
+ String s = "Javaプログラミング入門 2728円";
20
+ System.out.println(s);
21
+ System.out.println(s.replaceAll("\d++",
22
+ String.format("%,d", Integer.parseInt(s.replaceAll("\D", "")))
23
+ ));
24
+ }
25
+ }
26
+ ```
27
+ 実行結果
28
+ ```text
29
+ Javaプログラミング入門 2728円
30
+ Javaプログラミング入門 2,728円
31
+ ```

1

valueOf を parseInt に変更。NumberFormat のコードを追加

2020/12/23 07:28

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -1,5 +1,9 @@
1
- "$0" で正規表現を取得できるのは、replaceAll の第2引数に "$0" を書いた場合です。
1
+ replaceAll の第2引数に "$0" を書いた場合は、正規表現を取得きます。
2
- `new Integer("$0")` では、文字列 "$0" を int に変換できません。
2
+ new Integer("$0") では、文字列 "$0" を int に変換できません。
3
3
 
4
4
  "1000" を "1,000" に変換したいだけなら、
5
- `String.format("%,d", Integer.valueOf("1000"))` で済みます。
5
+ `String.format("%,d", Integer.parseInt("1000"))` で済みます。
6
+
7
+ repalceAll を使わずに、
8
+ `NumberFormat.getNumberInstance().format(Integer.parseInt("1000"))`
9
+ のようにもできますが、String.format の方が簡単でしょう。