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

标签 java string split

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

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/

相关文章:

java - 如何修复Android Studio中的Java堆大小问题

java - java中创建字符串对象

c - 尝试使用#define 将字符串数组分配给变量时出错(无效的初始值设定项错误)

javascript - 从 node.js 中的文件流中删除最后一个字符(fs 模块)

python - 拆分列表中的项目

r - 按R数据帧中数据 block 的长度生成随机数

java - IDEA "never accessed"关于增量运算符++的警告

java - 来自 SQLite 结果的 Android 自定义 ArrayAdapter

java - 编译 : tools. jar 未找到 fatal error :

php - 每隔一个空格拆分字符串以隔离每两个单词