到第n破折號後拆分,使用常規表達式找到要分裂的點並呼叫substring()
。只需將{}
之間的數字更改爲合適的n值即可。
(?:[^-]*-){2}
這裏是演示所有3個n:
String input = "BPI-1111-2203-4493";
Matcher m;
// Split on 1st dash
m = Pattern.compile("(?:[^-]*-){1}").matcher(input);
if (m.find())
System.out.printf("%s, %s%n", input.substring(0, m.end() - 1),
input.substring(m.end()));
// Split on 2nd dash
m = Pattern.compile("(?:[^-]*-){2}").matcher(input);
if (m.find())
System.out.printf("%s, %s%n", input.substring(0, m.end() - 1),
input.substring(m.end()));
// Split on 3rd dash
m = Pattern.compile("(?:[^-]*-){3}").matcher(input);
if (m.find())
System.out.printf("%s, %s%n", input.substring(0, m.end() - 1),
input.substring(m.end()));
輸出:
BPI, 1111-2203-4493
BPI-1111, 2203-4493
BPI-1111-2203, 4493
可以很容易地變成一個可重用的helper方法:
private static String[] split(String input, char ch, int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be >0");
Matcher m = Pattern.compile("(?:[^" + ch + "]*" + ch + "){" + n + "}").matcher(input);
if (! m.find())
return new String[] { input };
return new String[] { input.substring(0, m.end() - 1),
input.substring(m.end()) };
}
測試:
String input = "BPI-1111-2203-4493";
System.out.println(Arrays.toString(split(input, '-', 1)));
System.out.println(Arrays.toString(split(input, '-', 2)));
System.out.println(Arrays.toString(split(input, '-', 3)));
System.out.println(Arrays.toString(split(input, '-', 4)));
輸出:
[BPI, 1111-2203-4493]
[BPI-1111, 2203-4493]
[BPI-1111-2203, 4493]
[BPI-1111-2203-4493]
也可以按照suggestion by Jon Skeet和使用indexOf()
:
private static String[] split(String input, char ch, int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be >0");
int idx = 0;
for (int i = 0; i < n; i++)
if ((idx = input.indexOf(ch, idx) + 1) == 0)
return new String[] { input };
return new String[] { input.substring(0, idx - 1),
input.substring(idx) };
}
'indexOf'和'substring'? –
@JonSkeet如果我知道哪個'-',那很容易。但是「_nth'-'_」 – Hackerdarshi
你可以多次調用'indexOf',每次傳入前一個調用的結果來移動。 (查看'indexOf'的超載,它需要一個初始索引。) –