Iai*_*oat 4 python java string split
Java的字符串拆分(regex)函数在正则表达式的所有实例中拆分.Python的分区函数仅在给定分隔符的第一个实例处拆分,并返回{left,separator,right}的元组.
如何实现Java中的分区功能?
例如
"foo bar hello world".partition(" ")
Run Code Online (Sandbox Code Playgroud)
应该成为
"foo", " ", "bar hello world"
Run Code Online (Sandbox Code Playgroud)
是否有提供此实用程序的外部库?
没有外部库我怎么能实现呢?
它可以在没有外部库和没有Regex的情况下实现吗?
NB.我不是在寻找split("",2),因为它不会返回分隔符.
虽然不完全是你想要的,但还有第二个版本的split,它带有一个"limit"参数,告诉它将字符串拆分成的最大分区数.
所以如果你打电话(用Java):
"foo bar hello world".split(" ", 2);
Run Code Online (Sandbox Code Playgroud)
你得到了数组:
["foo", "bar hello world"]
Run Code Online (Sandbox Code Playgroud)
这或多或少是你想要的,除了分隔符没有嵌入索引1的事实.如果你真的需要这个最后一点,你需要自己做,但希望你特别想要的就是能够限制分裂的数量.
该String.split(String regex, int limit)接近你想要什么.从文档:
该
limit参数控制应用模式的次数,因此会影响结果数组的长度.
- 如果限制
n大于零,则模式将在大多数n - 1时间应用,数组的长度不会大于n,并且数组的最后一个条目将包含除最后一个匹配分隔符之外的所有输入.- 如果
n是非正数,那么模式将被应用尽可能多的次数,并且数组可以具有任何长度.
- 如果
n为零,则模式将被应用尽可能多次,数组可以具有任何长度,并且将丢弃尾随空字符串.
以下是显示这些差异的示例(如ideone.com上所示):
static void dump(String[] ss) {
for (String s: ss) {
System.out.print("[" + s + "]");
}
System.out.println();
}
public static void main(String[] args) {
String text = "a-b-c-d---";
dump(text.split("-"));
// prints "[a][b][c][d]"
dump(text.split("-", 2));
// prints "[a][b-c-d---]"
dump(text.split("-", -1));
// [a][b][c][d][][][]
}
Run Code Online (Sandbox Code Playgroud)
如果您需要与分区类似的功能,并且您还希望获得与任意模式匹配的分隔符字符串,则可以使用Matcher,然后使用substring适当的索引.
这是一个例子(如ideone.com上所示):
static String[] partition(String s, String regex) {
Matcher m = Pattern.compile(regex).matcher(s);
if (m.find()) {
return new String[] {
s.substring(0, m.start()),
m.group(),
s.substring(m.end()),
};
} else {
throw new NoSuchElementException("Can't partition!");
}
}
public static void main(String[] args) {
dump(partition("james007bond111", "\\d+"));
// prints "[james][007][bond111]"
}
Run Code Online (Sandbox Code Playgroud)
正则表达式\d+当然是任何数字字符(\d)重复一次或多次(+).