将一个字符串分割成N个字符串
我想将一个字符串拆分为 N 个 2char 字符串。我知道我必须使用 String.subSequence。但是我希望它继续创建这些直到字符串> 2
I want to split a string into N number of 2char strings. I know I must use String.subSequence. However I want it to keep creating these until the string is > 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
正则表达式的工作原理如下:从最后一个匹配位置 (
\ G
)并且在至少一个字符之前(零宽度正向前视(?=.)
)。这不应与字符串开头和结尾的位置匹配,因此 n 可以任意大,而不会导致开头或结尾出现空字符串。编辑:如果您想尽可能多地拆分,只需省略要拆分的第二个参数即可。
例子:
Try this:
The regex works as follows: find any position after 2 characters (zero-width postive look behind
(?<=...)
) starting from the last match position (\G
) and before at least one more character (zero-width positive look ahead(?=.)
). This should not match the positions at the start and end of the string and thus n can be as big as you want without resulting in an empty string at the start or the end.Edit: if you want to split as much as possible, just leave out the second parameter to split.
Example: