15
16

More than 5 years have passed since last update.

Java で任意の文字数で文字を分割

Posted at

○文字以降カットするのはよくやるけど、分割ってあんまりやったことなかったので、StringUtils とかひと通りライブラリを探した後で正規表現使えばいいことに気づきました。。

たとえば8文字で分割するならこう。

Matcher m = Pattern.compile("[\\s\\S]{1,8}").matcher("UMR、はい!!UMR、はい!!UMAじゃないようまる");
while (m.find()) {
    System.out.println(m.group());
}

出力:

UMR、はい!!
UMR、はい!!
UMAじゃないよ
うまる

.{1,8} でも良さそうですが、改行コードなどが端折られてしまうので、空白文字 \s と空白文字以外 \S にヒットさせています。

15
16
1

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
15
16