split,replaceAll,
java.lang.String split
String的split方法是直接按照给定的字符串对字符串进行拆分,例如
java 代码
?
?
运行结果:
a b c d e
但是在做ip解析时发现出了问题,代码如下:
java 代码
?
?
?
理想的输出结果应该是219 242 1 1,结果什么都没有输出。
很奇怪哦。看一下split的方法签名吧。
java 代码
?
?
?
这里的参数的名称是 regex ,也就是 Regular Expr<wbr>ession (正则表达式)。这个参数并不是一个简单的分割用的字符,而是一个正则表达式:</wbr>
java 代码
?
?
split 的实现直接调用的 Matcher 类的 split 的方法。“ . ”在正则表达式中有特殊的含义,因此我们使用的时候必须进行转义。
修改代码如下:
?
java 代码
?
?
?
Replace 方法
首先看看Replace方法的介绍
java 代码
?
?
?
a new String object is created that represents a character sequence identical to?
?
the character sequence represented by this String object, except that every?
?
occurrence of oldChar is replaced by an occurrence of newChar. Examples: "mesquite in your cellar".replace('e', 'o') returns "mosquito in your collar" "the war of baronets".replace('r', 'y') returns "the way of bayonets" "sparring with a purple porpoise".replace('p', 't') returns "starring with a turtle tortoise" "JonL".replace('q', 'x') returns "JonL" (no change) Parameters: oldChar the old character. newChar the new character. Returns: a string derived from this string by replacing every occurrence of oldChar with newChar.?
用法 :
java 代码
?
?
结果为:___ bCskd dkkAik kd_Fe
此方法用来替换char字符,对字符串不能处理
A.replace('aaa', '=') 是错误的
但是 A.replace(“aaa”, “=”)却是可以的
java 代码
?
?
结果为:= bCskd dkkAik k=Fe
可见 replace("","")与方法replaceAll("","")拥有差不多的功能
仔细看看差别
java 代码
?
?
?
with the specified literal replacement sequence. The replacement proceeds from?
?
the beginning of the string to the end, for example, replacing "aa" with "b" in?
?
the string "aaa" will result in "ba" rather than "ab". Parameters: target The sequence of char values to be replaced replacement The replacement sequence of char values Returns: The resulting string Throws: NullPointerException if target or replacement is null. Since: 1.5?
是1.5之后才有的功能哦
但是 replaceAll却更强大
java 代码
?
?
结果为aaabCskddkkAikkaaaFe
replaceAll可以将字符串内部的空格去掉
但是用replace(' ','')方法却不可以
replace(" ","")方法可以
另外一点
java 代码
?
?
结果为:=== =C=== ===A== ====F=
replaceAll可以用正则表达式,强大啊
我们看看replaceAll的用法
java 代码
?
?
?
with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly?
?
the same result as the expression java.util.regex.Pattern. compile(regex).java.util.regex.Pattern.matcher(java.lang.CharSequence) matcher(str). replaceAll(repl) See Also: java.util.regex.Pattern Parameters: regex the regular expression to which this string is to be matched Returns: The resulting String Throws: PatternSyntaxException if the regular expression's syntax is invalid Since: 1.4 @spec JSR-51参考:http://blog.163.com/zzcc_8/blog/static/1603547220101111147830/
?
?
??
Illegal group reference异常
?
String replaceAll(regex, replacement)函数 ,? 由于第一个参数支持正则表达式,replacement中出现“$”,会按照$1$2的分组模式进行匹配,当编译器发现“$”后跟的不是整数的时候,就会抛出“非法的组引用”的异常。
解决办法一,直接用replace()方法替换,就不会有这样的问题;二,对'$'进行转义,参考:http://gongmingwind.iteye.com/blog/254325?