且构网

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

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

更新时间:2022-06-14 21:20:15

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

Here's the regex one-liner version:

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

\G 是一个零宽度断言,匹配前一个匹配结束的位置.如果 was 没有之前的匹配项,则匹配输入的开头,与 \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 支持后视也不能这样使用.

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 中不起作用,它不支持在lookbehinds 中使用 \G.

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