温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用java regex分割字符串

发布时间:2026-10-04 22:38:18 来源:亿速云 阅读:90 作者:小樊 栏目:编程语言

在 Java 中,使用 正则表达式(regex)分割字符串 通常有两种常见方式:


一、使用 String.split(Regex)

这是最简单、最常用的方式。

基本用法

String text = "apple,banana;orange|grape";
String[] result = text.split("[,;|]");

for (String s : result) {
    System.out.println(s);
}

输出:

apple
banana
orange
grape

说明

  • [,;|] 表示 逗号、分号或竖线 任意一个
  • 返回值是 String[]

二、使用 Pattern + Matcher(更灵活)

适合复杂分割、捕获分组、流式处理等场景。

示例:按一个或多个空格分割

import java.util.regex.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String text = "a   b    c	d";
        Pattern pattern = Pattern.compile("\\s+");
        String[] result = pattern.split(text);

        System.out.println(Arrays.toString(result));
    }
}

三、常见正则分割示例

1️⃣ 按一个或多个空格

text.split("\\s+");

2️⃣ 按数字分割

text.split("\\d+");

3️⃣ 按多个分隔符

text.split("[,;:|]");

4️⃣ 限制分割次数

text.split(",", 2);

只分割前 1 次


四、注意事项(很重要)

⚠️ 正则特殊字符需要转义

text.split("\\.");   // 按点分割
text.split("\\|");   // 按竖线

⚠️ 空字符串问题

"a,,b".split(",");

结果:

["a", "", "b"]

如果结尾有空字符串:

"a,b,".split(",");

结果:

["a", "b"]

(Java 默认去掉末尾空串)


五、进阶:使用 Matcher 提取而不是分割

Pattern p = Pattern.compile("\\w+");
Matcher m = p.matcher("abc 123 def");

while (m.find()) {
    System.out.println(m.group());
}

如果你有具体字符串和分割规则(比如日志、CSV、表达式),可以直接贴出来,我可以帮你写精确的正则。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手