java - Java中如何分割字符串?

标签 java string split

我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:

part1 = "004";
part2 = "034556";

这意味着第一个字符串将包含 '-' 之前的字符,第二个字符串将包含 '-' 之后的字符。

我还想检查字符串中是否有 '-'

最佳答案

使用适当命名的方法 String#split() .

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

请注意split的参数假定为 regular expression ,所以记得逃跑special characters如果需要的话。

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

例如,按句点/点分割 . (在正则表达式中表示“any character ”),使用 backslash \ 像这样转义单个特殊字符 split("\\.") ,或使用character class [] 像这样表示文字字符 split("[.]") ,或使用 Pattern#quote() 像这样转义整个字符串 split(Pattern.quote(".")) .

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

要预先测试字符串是否包含某些字符,只需使用 String#contains() .

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

请注意,这不需要正则表达式。为此,请使用 String#matches() 相反。

如果您想在结果部分中保留分割字符,请使用 positive lookaround 。如果您想让分割字符最终出现在左侧,请通过添加前缀 ?<= 来使用正向后查找。对模式进行分组。

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

如果您希望分割字符出现在右侧,请通过添加前缀 ?= 使用正向前瞻。对模式进行分组。

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

如果您想限制结果部分的数量,那么您可以提供所需的数量作为 split() 的第二个参数方法。

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42

关于java - Java中如何分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46350950/

相关文章:

Java:JScrollPane 不适用于 GridBagLayout

java - 在电话间隙中通过 Ajax 实现 JSON 效果不佳

javascript - 为什么 string.split() 对于正则表达式的行为不同?

c# - string.Split 即使有效也会产生错误

regex - 如何检查字符串是否包含 shell 中正则表达式模式中的字符?

linux - 如何在文件中查找文本并根据模式上下排列

java - 遍历 Collection<List<Integer>>

java - Stream 内的 Bigdecimal 求和

string - 如何在golang中读取 "\t"作为标签

java - 在输入回收器 View 时如何避免 Activity 中出现硬编码字符串?