Java中正则表达式split()特殊符号使用详解
特殊情况有*^:|.\
一、单个符号作为分隔符
- Stringaddress="上海\上海市|闵行区\吴中路";
String[]splitAddress=address.split("\\"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- Stringaddress="上海|上海市|闵行区|吴中路";
String[]splitAddress=address.split("\\|");//如果以竖线为分隔符,则split的时候需要加上两个斜杠【\\】进行转义 System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- Stringaddress="上海*上海市*闵行区*吴中路";
String[]splitAddress=address.split("\\*"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- Stringaddress="上海:上海市:闵行区:吴中路";
String[]splitAddress=address.split("\\:"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- Stringaddress="上海.上海市.闵行区.吴中路";
String[]splitAddress=address.split("\\."); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- Stringaddress="上海^上海市^闵行区^吴中路";
String[]splitAddress=address.split("\\^"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- Stringaddress="上海@上海市@闵行区@吴中路";
String[]splitAddress=address.split("@"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- Stringaddress="上海,上海市,闵行区,吴中路";
String[]splitAddress=address.split(","); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
二、多个符号作为分隔符
Stringaddress="上海^上海市@闵行区#吴中路";
String[]splitAddress=address.split("\\^|@|#"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
例:
Stringaddress=newString("192.168.13.240"); String[]str=address.split("\\."); for(Strings:str){ System.out.println(s); }
输出格式:
192
168
13
240
总结:
(1)split表达式,其实就是一个正则表达式。*^|等符号在正则表达式中属于一种有特殊含义的字符,如果使用此种字符作为分隔符,必须使用转义符即\\加以转义。
(2)如果使用多个分隔符则需要借助|符号,如二所示,但需要转义符的仍然要加上分隔符进行处理
到此这篇关于Java中正则表达式split()特殊符号使用详解的文章就介绍到这了,更多相关Javasplit()内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!