質問

I have the following string:

String x = "020120765";

I want this string in the form of 02 0120765. One possibility is:

x = x.substring(0,2) + " " + x.substring(2, x.length());

or:

x = String.format("%s %s", x.substring(0, 2), x.substring(2));

Is there any other better or elegant way? I'm thinking in the direction of regex. I have tried the following:

x = String.format("%s %s", x.split("\\d{2}"));

But it doesn't work.

役に立ちましたか?

解決 2

Another option

x = x.replaceAll("(..)(.+)", "$1 $2");

他のヒント

You could also use a StringBuilder with its insert method:

x = new StringBuilder(x).insert(2, ' ').toString();

If you are interested in regex solution then you can try with

x = x.replaceAll("^..", "$0 ")

^.. will match first first two characters. $0 is reference to match from group 0 (which contains entire match) so $0will replace matched part with itself plus space.

x=String.format("%s %s",x.split("(?<=\\G.{2})", 2))

will not work because you are trying to pass an array in and you have too few arguments. You could, however, do it like this:

x=String.format("%s %s",x.split("(?<=\\G.{2})", 2)[0], x.split("(?<=\\G.{2})", 2)[1]);

Or, more neatly,

String[] arr = x.split("(?<=\\G.{2})", 2);
x = String.format("%s %s", arr[0], arr[1]);

EDIT: I am very inexperienced with regex so please excuse the previous incorrect regex patterns.

x.replaceAll("(?<=^..)", " ");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top