Java和字符串拆分 [英] Java and string split

查看:92
本文介绍了Java和字符串拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用函数拆分拆分此String。这是我的代码:

split this String using function split. Here is my code:

String data= "data^data";
String[] spli = data.split("^");

当我尝试在spli中只包含一个字符串时。看起来java在拆分时看不到^。有谁知道我怎么能用字母^分割这个字符串?

When I try to do that in spli contain only one string. It seems like java dont see "^" in splitting. Do anyone know how can I split this string by letter "^"?

编辑

求助:P

推荐答案

这是因为 String.split 采用正则表达式,而不是文字字符串。您必须转义 ^ ,因为它在正则表达式中具有不同的含义(在字符串的开头处为锚点)。因此,拆分实际上将在第一个字符之前完成,为您提供完整的字符串保持不变。

This is because String.split takes a regular expression, not a literal string. You have to escape the ^ as it has a different meaning in regex (anchor at the start of a string). So the split would actually be done before the first character, giving you the complete string back unaltered.

您使用 \转义正则表达式元字符,在Java字符串中必须是 \\ ,所以

You escape a regular expression metacharacter with \, which has to be \\ in Java strings, so

data.split("\\^")

应该工作。

这篇关于Java和字符串拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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