仅在第一个实例上拆分字符串 - java [英] split string only on first instance - java

查看:29
本文介绍了仅在第一个实例上拆分字符串 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 '=' 字符分割一个字符串.但我希望它只在第一个实例中拆分.我怎样才能做到这一点 ?这是'_'字符的JavaScript示例,但对我不起作用仅在指定字符的第一个实例上拆分字符串

I want to split a string by '=' charecter. But I want it to split on first instance only. How can I do that ? Here is a JavaScript example for '_' char but it doesn't work for me split string only on first instance of specified character

示例:

apple=fruit table price=5

当我尝试 String.split('=');它给

When I try String.split('='); it gives

[apple],[fruit table price],[5]

但我需要

[apple],[fruit table price=5]

谢谢

推荐答案

string.split("=", 2);

作为 String.split(java.lang.String regex, int limit) 解释:

As String.split(java.lang.String regex, int limit) explains:

此方法返回的数组包含此字符串的每个子字符串,这些子字符串由与给定表达式匹配的另一个子字符串终止,或由字符串末尾终止.数组中的子字符串按它们在此字符串中出现的顺序排列.如果表达式不匹配输入的任何部分,则结果数组只有一个元素,即这个字符串.

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

limit 参数控制应用模式的次数,因此会影响结果数组的长度.如果限制 n 大于零,则该模式将被应用至多 n - 1 次,数组的长度将不大于 n,并且数组的最后一个条目将包含最后一个匹配的分隔符之外的所有输入.

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.

例如,字符串 boo:and:foo 使用这些参数产生以下结果:

The string boo:and:foo, for example, yields the following results with these parameters:

Regex Limit    Result
:     2        { "boo", "and:foo" }
:     5        { "boo", "and", "foo" }
:    -2        { "boo", "and", "foo" }
o     5        { "b", "", ":and:f", "", "" }
o    -2        { "b", "", ":and:f", "", "" }
o     0        { "b", "", ":and:f" }

这篇关于仅在第一个实例上拆分字符串 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆