關於split遇到的一個奇葩問題

split用於分割字符串獲得字串數組這是基本用法。以下:數組

def str= "3 2"
if(str.contains(" ")){
    println str.split(' ')[0] // 3
}函數

但是換一種狀況:blog

def str= "3+2"
if(str.contains("+")){
    println str.split('+')[0] //報錯
}字符串

 

卻報錯了!get

image

百度查清楚緣由發現:it

出現+、*、|、/ 等正則中使用的特殊字符。split函數把"+"看成正則處理了。

只須要加[] 便可百度

def str= "3+2" if(str.contains("+")){     println str.split('[+]')[0]  //能夠正常輸出 }
相關文章
相關標籤/搜索