我需要将字符串分成两部分,例如:
String myString = "the_string";
String splitted[] = myString.split("_");
没问题,但如果我的字符串包含以下内容:myString = "the____string";
它不起作用,我不知道如何确保这一点,谢谢;
最佳答案
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"]
关于java - String.split更多正则表达式字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20359516/