java中的Split()-ing
假设我有:
String string1 = "123,234,345,456,567*nonImportantData";
String[] stringArray = string1.split(", ");
String[] lastPart = stringArray[stringArray.length-1].split("*");
stringArray[stringArray.length-1] = lastPart[0];
有没有更简单的方法可以让这段代码工作?我的目标是分离所有数字,无论 stringArray 是否包含 nonImportantData。我应该使用子字符串方法吗?
So let's say I have:
String string1 = "123,234,345,456,567*nonImportantData";
String[] stringArray = string1.split(", ");
String[] lastPart = stringArray[stringArray.length-1].split("*");
stringArray[stringArray.length-1] = lastPart[0];
Is there any easier way of making this code work? My objective is to get all the numbers separated, whether stringArray includes nonImportantData or not. Should I maybe use the substring method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,String.split(...) 方法的参数不是分隔符字符串,而是正则表达式。
您可以使用
where |是正则表达式 OR,\\ 用于转义 *,因为它是正则表达式中的特殊运算符。您的 split("*") 实际上会抛出 java.util.regex.PatternSyntaxException 。
Actually, the String.split(...) method's argument is not a separator string but a regular expression.
You can use
where | is a regexp OR and \\ is used to escape * as it is a special operator in regexp. Your split("*") would actually throw a java.util.regex.PatternSyntaxException.
假设您始终拥有您提供的格式......
Assuming you always have the format you've provided....
在分割字符串之前我可能会删除不重要的数据。
如果
'*'
始终存在,您可以像这样缩短它:这与 MarianP 的方法,因为“不重要的数据”不会保留为数组的元素。这可能有帮助,也可能没有帮助,具体取决于您的应用程序。
I'd probably remove the unimportant data before splitting the string.
If
'*'
is always present, you can shorten it like this:This is different than MarianP's approach because the "unimportant data" isn't preserved as an element of the array. This may or may not be helpful, depending on your application.