在Java中将字符串拆分为相等长度的子字符串 [英] Split string to equal length substrings in Java

查看:180
本文介绍了在Java中将字符串拆分为相等长度的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串Thequickbrownfoxjumps拆分为Java中相等大小的子字符串。
例如。 4个相等大小的thequickbrownfoxjumps应该给出输出。

How to split the string "Thequickbrownfoxjumps" to substrings of equal size in Java. Eg. "Thequickbrownfoxjumps" of 4 equal size should give the output.

["Theq","uick","brow","nfox","jump","s"]

类似问题:

将字符串拆分为Scala中的等长子串

推荐答案

这是正则表达式的单行版本:

Here's the regex one-liner version:

System.out.println(Arrays.toString(
    "Thequickbrownfoxjumps".split("(?<=\\G.{4})")
));

\ G 是零宽度与前一个匹配结束的位置匹配的断言。如果 之前没有匹配,则它与输入的开头匹配,与 \A 相同。封闭的lookbehind匹配从最后一场比赛结束开始的四个字符的位置。

\G is a zero-width assertion that matches the position where the previous match ended. If there was no previous match, it matches the beginning of the input, the same as \A. The enclosing lookbehind matches the position that's four characters along from the end of the last match.

两个lookbehind和 \G 是高级正则表达式功能,并非所有版本都支持。此外, \ G 并未在支持它的各种风格中实现一致。这个技巧(例如)可以在 Java ,Perl,.NET和JGSoft中使用,但不能在 PHP (PCRE),Ruby 1.9+或TextMate(都是Oniguruma)。 JavaScript的 / y (粘性标记)不如 \ G 灵活,并且无法使用此即使JS支持lookbehind也是如此。

Both lookbehind and \G are advanced regex features, not supported by all flavors. Furthermore, \G is not implemented consistently across the flavors that do support it. This trick will work (for example) in Java, Perl, .NET and JGSoft, but not in PHP (PCRE), Ruby 1.9+ or TextMate (both Oniguruma). JavaScript's /y (sticky flag) isn't as flexible as \G, and couldn't be used this way even if JS did support lookbehind.

我应该提一下,如果你有其他选择,我不一定推荐这个解决方案。其他答案中的非正则表达式解决方案可能更长,但它们也是自我记录的;这个只是与相反的。 ;)

I should mention that I don't necessarily recommend this solution if you have other options. The non-regex solutions in the other answers may be longer, but they're also self-documenting; this one's just about the opposite of that. ;)

此外,这在Android中不起作用,Android不支持使用 \ G 在外观中。

Also, this doesn't work in Android, which doesn't support the use of \G in lookbehinds.

这篇关于在Java中将字符串拆分为相等长度的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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