且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中将字符串拆分为相等长度的子字符串

更新时间:2021-11-29 22:32:43

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

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.