我需要将我的字符串拆分为两个,例如:
String myString = "the_string";
String splitted[] = myString.split("_");
没关系,但是如果我的字符串包含这个:myString = "the____string";
它不工作,我不知道如何确保这一点,谢谢;
答案 0 :(得分:3)
String.split
的分隔符参数是正则表达式。如果要拆分其中一个下划线,请使用myString.split("_+")
。
如果您的结果中始终需要两个元素,而不管分隔符的重复实例,myString.split("_+", 2)
String a = "hello_there"
String b = "hello___there"
String c = "hello____there___how__are_you"
a.split("_+"); // -> ["hello", "there"]
b.split("_+"); // -> ["hello", "there"]
c.split("_+"); // -> ["hello", "there", "how", "are", "you"]
a.split("_+", 2); // -> ["hello", "there"]
b.split("_+", 2); // -> ["hello", "there"]
c.split("_+", 2); // -> ["hello", "there___how__are_you"]