你能在String split中使用零宽度匹配正则表达式吗? [英] Can you use zero-width matching regex in String split?

查看:113
本文介绍了你能在String split中使用零宽度匹配正则表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.out.println(
    Arrays.deepToString(
        "abc<def>ghi".split("(?:<)|(?:>)")
    )
);

打印 [abc,def,ghi] ,好像我已经拆分< |>。我希望它打印 [abc,< def>,ghi] 。有没有办法使用一些正则表达式魔法来完成我想要的东西?

This prints [abc, def, ghi], as if I had split on "<|>". I want it to print [abc, <def>, ghi]. Is there a way to work some regex magic to accomplish what I want here?

也许是一个更简单的例子:

Perhaps a simpler example:

System.out.println(
    Arrays.deepToString(
        "Hello! Oh my!! Good bye!!".split("(?:!+)")
    )
);

打印 [Hello,Oh my,Good bye] 。我希望它打印 [你好!,我的!!,再见!!]
`。

This prints [Hello, Oh my, Good bye]. I want it to print [Hello!, Oh my!!, Good bye!!]. `.

推荐答案

感谢来自Cine的信息,我认为这些都是答案我正在寻找:

Thanks to information from Cine, I think these are the answers I'm looking for:

System.out.println(
    Arrays.deepToString(
        "abc<def>ghi<x><x>".split("(?=<)|(?<=>)")
    )
); // [abc, <def>, ghi, <x>, <x>]


System.out.println(
    Arrays.deepToString(
        "Hello! Oh my!! Good bye!! IT WORKS!!!".split("(?<=!++)")
    )
); // [Hello!,  Oh my!!,  Good bye!!,  IT WORKS!!!]

现在,通过试验所有不同的量词,真实地发现了第二个。无论是贪婪还是不情愿的工作,都是占有欲的。

Now, the second one was honestly discovered by experimenting with all the different quantifiers. Neither greedy nor reluctant work, but possessive does.

我仍然不确定原因。

这篇关于你能在String split中使用零宽度匹配正则表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆