java - 仅拆分字符串两次

标签 java regex string split

我有一个类似 abc~def~ghij~klm~nop~qrstu~vwx~hj 的字符串。我只想将它拆分两次(结果分为三部分):这意味着无论我在哪里得到 ~ 符号,我都需要拆分 abcdef 第三个仅作为单个字符串 ghij~klm~nop~qrstu~vwx~hj

我知道如何在 ~ 符号出现的地方拆分成字符串

String[] parts = stat.split("~");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];

这里我只得到第 3 部分作为 ghij,我需要整个字符串用 ~ 符号保持长。

最佳答案

这只会将 stat 字符串拆分两次,即将其拆分为 3 部分:

String[] parts = stat.split("~", 3);

String.split(String regex, int limit)方法允许控制结果部分的数量。

引用 Javadoc:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

关于java - 仅拆分字符串两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32349245/

相关文章:

java - 在 Android 上查找应用程序的 CPU 使用率

java - Apache Mina Java FTP 服务器实现 - 客户端卡在等待欢迎消息

c++ - 在 C++ 程序中使用 for 循环的问题负责查找 XML 文件中包含 25 个数值的 6 行中每一行的平均值

javascript - 如何匹配正则表达式中 < & > 之间的任何内容?

C 的字符和字符串

java - 尝试使用 DAO 查找用户时出现 NullPointerException

java - 线程代码中的 NullPointerException 导致线程终止

C# - 用下划线和字母替换每个大写字母

javascript - 为什么 'a' > 'A' 是真的?

c++ - 字符数组和指针的基本混淆