gpt4 book ai didi

java - String.split更多正则表达式字符

转载 作者:行者123 更新时间:2023-12-01 23:23:23 25 4
gpt4 key购买 nike

我需要将字符串分成两部分,例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com