一、各類(lèi)空白分隔符介紹
\t:制表符,相當(dāng)于tab
\n:換行
\r:回車(chē)
\f:換頁(yè)
\s:在java正則表達(dá)式常見(jiàn),例如java的匹配、替換、分割字符串(matches,split)
例:
"Java is fun".matches("Java.*") //返回true
二、正確使用split來(lái)分割空白字符
public class demo {
? ? public static void main(String[] args) ?{
? ? ? ? String line = new Scanner(System.in).nextLine();
? ? ? ? String[] s1 = line.split(" ");
? ? ? ? String[] s2 = line.split("\\t");
? ? ? ? String[] s3 = line.split("\\s");
? ? ? ? String[] s4 = line.split("\\s+");
? ? ? ? System.out.print("一個(gè)空格:");
? ? ? ? for(String s : s1) {
? ? ? ? ? ? System.out.print(s + ",");
? ? ? ? }
? ? ? ? System.out.println("\n------------------------------->=_=");
? ? ? ? System.out.print("\\t:");
? ? ? ? for(String s : s2) {
? ? ? ? ? ? System.out.print(s + ",");
? ? ? ? }
? ? ? ? System.out.println("\n------------------------------->=_=");
? ? ? ? System.out.print("\\s:");
? ? ? ? for(String s : s3) {
? ? ? ? ? ? System.out.print(s + ",");
? ? ? ? }
? ? ? ? System.out.println("\n------------------------------->=_=");
? ? ? ? System.out.print("\\s+:");
? ? ? ? for(String s : s4) {
? ? ? ? ? ? System.out.print(s + ",");
? ? ? ? }
? ? }
}
輸入:hello my ?lovely ? ?world! ? ? ? (分別為一個(gè)空格、兩個(gè)空格 和 一個(gè)制表符)
三、\\s的使用說(shuō)明
1、\\s而不是\s:
反斜杠是一個(gè)特殊的字符,在字符串中開(kāi)始轉(zhuǎn)義序列。" \ "號(hào)的在正則中被賦予了特殊含義,這時(shí),就需要在造成歧義的字符前加\,來(lái)告訴編譯器:這個(gè)字符只是一個(gè)普通字符。所以當(dāng)我們想在正則中匹配”\s”時(shí),需要加上轉(zhuǎn)義變成了“\\s"。
2、\s和\t\n\r\f及' '的關(guān)系:
空白字符是' '、'\t'、'\n'、'\r',或者'\f'。因此,用[\t\n\r\f]來(lái)表示空白,而\s和[\t\n\r\f]等同。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-607597.html
3、\\s+:
在java的正則表達(dá)式中,p*代表模式p的0或多次出現(xiàn),p+代表模式p的1或者多次出現(xiàn),p?代表模式p的0次或者1次出現(xiàn)。所以我們?cè)谧鲱}時(shí)候通常用的是\s+。就如上面的代碼一樣,\s在處理連續(xù)多個(gè)空格時(shí),會(huì)出現(xiàn)問(wèn)題,需要使用\s+。
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-607597.html
到了這里,關(guān)于Java中split分割帶空格的字符串 \t \n \r \f 及 \s 的區(qū)別的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!