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

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

问题描述

如何在 Java 中将字符串 "Thequickbrownfoxjumps" 拆分为相同大小的子字符串.例如."Thequickbrownfoxjumps" 4 等大小应该给出输出.

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 是一个零宽度断言,匹配前一个匹配结束的位置.如果 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.

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

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