信息发布→ 登录 注册 退出

java关于String.split("|")的使用方式

发布时间:2026-01-11

点击量:
目录
  • String.split("|")的使用
    • 我们先来写一段代码测试一下
    • 你知道结果是什么吗?
  • String.split() 特殊字符处理
    • split函数
    • 特殊符号的处理
    • 示例

String.split("|")的使用

我们先来写一段代码测试一下

public class TestSplit {
    public static void main(String[] a){
        String test = "中文|英文";
        print(test.split("|"));
        print(test.split(""));
        print(test.split("\\|"));
    }
    public static void print(String[] a){
        System.out.println("============================");
        for(String i:a){
            System.out.println(i);
        }
        System.out.println("============================\n");
    }
}

你知道结果是什么吗?

如下:

============================



|


============================

============================



|


============================

============================
中文
英文
============================

所以我们从上面可以知道:“|”和“”的效果是一样的,如果你要得到正确的结果你必须这样“\|”,双引号里面的是一个正则表达式。

String.split() 特殊字符处理

  • jdk 1.8

split函数

注意,split函数的参数是正则表达式。split函数的定义为:

/**
 * Splits this string around matches of the given <a
 * href="../util/regex/Pattern.html#sum" rel="external nofollow" >regular expression</a>.
 *
 * <p> This method works as if by invoking the two-argument {@link
 * #split(String, int) split} method with the given expression and a limit
 * argument of zero.  Trailing empty strings are therefore not included in
 * the resulting array.
 *
 * <p> The string {@code "boo:and:foo"}, for example, yields the following
 * results with these expressions:
 *
 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
 * <tr>
 *  <th>Regex</th>
 *  <th>Result</th>
 * </tr>
 * <tr><td align=center>:</td>
 *     <td>{@code { "boo", "and", "foo" }}</td></tr>
 * <tr><td align=center>o</td>
 *     <td>{@code { "b", "", ":and:f" }}</td></tr>
 * </table></blockquote>
 *
 *
 * @param  regex
 *         the delimiting regular expression
 *
 * @return  the array of strings computed by splitting this string
 *          around matches of the given regular expression
 *
 * @throws  PatternSyntaxException
 *          if the regular expression's syntax is invalid
 *
 * @see java.util.regex.Pattern
 *
 * @since 1.4
 * @spec JSR-51
 */
public String[] split(String regex) { ... }

特殊符号的处理

split函数的参数是正则表达式,则正则表达式的特殊符号作为分隔符时,就需要特殊处理。

比如,.在正则表达式中是通配符,匹配除换行符(\n、\r)之外的任何单个字符。

对特殊符号的处理方法有两种:

  • 转义。比如,\.
  • 放到中括号里。比如,[.]

示例

String[] s1 = "a.b.c".split("\\.");
System.out.println(Arrays.asList(s1)); //[a, b, c]
String[] s2 = "a.b.c".split("[.]");
System.out.println(Arrays.asList(s2)); //[a, b, c]

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!