Java split 分割 字符串(分隔符如:* ^ : | , .) 及注意点 要转义

2021-04-21 15:28

阅读:594

标签:add   转义   正则表达   就是   符号   必须   注意   上海   需要   

split 分割 字符串(分隔符如:* ^ : | , .) 及注意点

split表达式,其实就是一个正则表达式。【 * ^ | 】等符号在正则表达式中属于一种有特殊含义的字符,如果使用此种字符作为分隔符,必须使用转义符即【 \\ 】加以转义。

String address=”上海|上海市|闵行区|吴中路”;
String[] splitAddress=address.split(“\\|”); //如果以竖线为分隔符,则split的时候需要加上两个斜杠【\\】进行转义
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
    
String address=”上海*上海市*闵行区*吴中路”;
String[] splitAddress=address.split(“\\*”);
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
    
String address=”上海:上海市:闵行区:吴中路”;
String[] splitAddress=address.split(“\\:”);
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);

String address=”上海.上海市.闵行区.吴中路”;
String[] splitAddress=address.split(“\\.”);
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
    
String address=”上海^上海市^闵行区^吴中路”;
String[] splitAddress=address.split(“\\^”);
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
    
String address=”上海@上海市@闵行区@吴中路”;
String[] splitAddress=address.split(“@”);
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
    
String address=”上海,上海市,闵行区,吴中路”;
String[] splitAddress=address.split(“,”);
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);

如果使用多个分隔符则需要借助 | 符号,但需要转义符的仍然要加上分隔符进行处理。

String address=”上海^上海市@闵行区#吴中路”;
String[] splitAddress=address.split(“\\^|@|#”);
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);

Java split 分割 字符串(分隔符如:* ^ : | , .) 及注意点 要转义

标签:add   转义   正则表达   就是   符号   必须   注意   上海   需要   

原文地址:https://www.cnblogs.com/that-jay/p/13280995.html


评论


亲,登录后才可以留言!