您可以在字符串拆分中使用零宽度匹配正则表达式吗? [英] Can you use zero-width matching regex in 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]
.我想让它打印 [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.
我仍然不知道为什么.
这篇关于您可以在字符串拆分中使用零宽度匹配正则表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!