25
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaで文字列を「.(ドット)」でsplitする

Posted at

久しぶりにJavaを書いていて.で文字列を区切ろうとしたら軽くハマった。

Pythonならこんな感じ。

hoge = '172.0.0.1'
fuga = hoge.split('.') # => ['172', '0', '0', '1']

同じ感覚でJavaで

String hoge = "172.0.0.1";
String[] fuga = hoge.split(".");

と書いてしまうと、長さ0の配列が返ってくる。

原因はJavaのsplitは引数にpattern文字列をとるから。
.は任意の一文字にマッチしてしまう。( ..)φメモメモ

String hoge = "172.0.0.1";
String[] fuga = hoge.split("7."); // => ["1", ".0.0.1"]

Pythonと同じ動作を期待するならこう。

import java.util.regex.Pattern;

String hoge = "172.0.0.1";
String[] fuga = hoge.split(Pattern.quote("."));
25
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?