使用split将字符串拆分为2个字符的组? [英] Split a string to groups of 2 chars using split?

查看:257
本文介绍了使用split将字符串拆分为2个字符的组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的字符串:

I have this simple string :

a1a2a3

是否有任何正则表达式可以与 split 命令一起使用,以便将字符串拆分为一对? :

Is there any regex expression which can be used with split command so it will split the string to a pairs ? :

[a1,a2,a3]

我试过这个:

a1a2a3.split(/(?=。/)/)

但它返回 [a,1,a,2,a3 ]

ps

我可以用匹配但正在查找(如果存在)正则表达式,它可以帮助我使用 split

I can do it with Match but im looking (if exists) for the regex expression which can help me using split.

推荐答案

拆分获取偶数长度字符串:

split for even length string:

str.split(/(?=(?:..)*$)/)

split 对于奇数长度的字符串,最后一个条目有单个字符:

split for odd length string, the last entry has single character:

str.split(/(?=(?:..)*.$)/)

这些基本上是先行,检查前面的字符数是奇数还是偶数。它利用了以下事实:所有分割位置前面的字符数与字符串长度具有相同的奇偶校验。

Those are basically look-aheads that check whether the number of characters ahead is odd or even. It takes advantage of the fact that the number of characters ahead at all the split positions have the same parity as the length of the string.

(偶数版本)中的模式)预见是(?:..)* $ ,它检查偶数个字符(?:..)* 在字符串 $ 结尾之前。 (请注意,此处使用非捕获组(?: pattern),否则捕获组将在拆分结果)。类似的解释适用于奇数版本。

The pattern in the (even version) look-ahead is (?:..)*$, which checks for even number of characters (?:..)* before the end of the string $. (Note that non-capturing group (?:pattern) is used here, otherwise, capturing group will create extra entries in the split result). Similar explanation applies for the odd version.

请注意 排除了几个新的换行符 \ n \ r \ u2028 \ u2029 。它会对包含这些字符的字符串产生意外结果。将替换为 [\\\\ S] (或其他等效构造),使其适用于所有情况。

Note that . excludes several new line characters: \n, \r, \u2028 or \u2029. It will produce unexpected result for string containing such characters. Replace . with [\s\S] (or other equivalent construct) to make it works for all cases.

出于实用目的,匹配是正确的工具工作:

For practical purpose, match is the right tool for the job:

str.match(/..?/g)

例如:

"1234567890".match(/..?/g)
> [ "12", "34", "56", "78", "90" ]

"1234567890".match(/..?/g)
> [ "12", "34", "56", "78", "9" ]

该解决方案可以扩展为n个字符组:

The solution can be extended to group of n characters:

str.match(/.{1,<n>}/g)

例如:

"123456789012345678901234567890".match(/.{1,7}/g)
> [ "1234567", "8901234", "5678901", "2345678", "90" ]

它只是利用贪婪的量词并创建n个字符的组,然后用完字符以匹配最后一个组。

It simply takes advantage of the greedy quantifier and creates groups of n characters, before running out of characters to match for the last group.

与上面相同,你可能想要将更改为 [\\\ S] ,以使其适用于所有情况。

Same as above, you may want to change . to [\s\S] to make it work for all cases.

这篇关于使用split将字符串拆分为2个字符的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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