我有一个字符串,"004-034556"
,我想分成两个字符串:
string1="004";
string2="034556";
这意味着第一个字符串将包含
'-'
之前的字符。 , 第二个字符串将包含 '-'
之后的字符.我还想检查字符串是否有 '-'
在里面。如果没有,我会抛出一个异常。我怎样才能做到这一点?
最佳答案
只需使用适当的方法: String#split()
.
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
请注意,这需要 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".
所以,如果你想 split 例如周期/点
.
这意味着“any character”在正则表达式中,使用 backslash \
像这样转义单个特殊字符 split("\\.")
, 或使用 character class []
像这样表示文字字符split("[.]")
, 或使用 Pattern#quote()
像这样转义整个字符串 split(Pattern.quote("."))
.String[] parts = string.split(Pattern.quote(".")); // Split on period.
要预先测试字符串是否包含某些字符,只需使用
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/60063606/