我有一个字符串'OR-xxxxxxxxx-001-01'。我需要将其拆分为"OR-xxxxxxxx-001"one_answers"01"。是否可以不使用"-"拆分并再次连接??
在Java中,使用lastIndexOf
:
String string = "OR-xxxxxxxx-001-01";
int lastDash = string.lastIndexOf('-');
String prefix = string.substring(0, lastDash); // OR-xxxxxxx-001
String suffix = string.substring(lastDash + 1); // 01
此解决方案适用于JavaScript(Java和JavaScript不是一回事(。
由于您不想按进行拆分,因此可以使用索引进行拆分。你还没有指定它是否是固定长度的(这个解决方案取决于它(,但这应该可以做到:
t = 'OR-xxxxxxxx-001-01'
str = t.slice(0, 12) + t.slice(16);
将给出str = 'OR-xxxxxxxx-01'
您可以使用具有积极前瞻性的拆分:
String str = "OR-xxxxxxxx-001-01";
String[] split = str.split("-(?=[^-]+$)");
[^-]
:除-
之外的任何字符+
:重复一次或多次$
:在字符串末尾- 然后
(?= ... )
用于正面展望,因此它不会被拆分删除。这意味着只有括号外的-
作为分隔符进行拆分
在线试用
PS:在Java中。