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

查看:49
本文介绍了使用拆分将字符串拆分为 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"]

附上

我可以用 Match 做到这一点,但我正在寻找(如果存在)正则表达式,它可以帮助我使用 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:

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.

(偶数版本)前瞻中的模式是(?:..)*$,它检查偶数个字符(?:..)*code> 在字符串 $ 的结尾之前.(注意这里使用的是非捕获组(?:pattern),否则捕获组会在split结果中创建额外的条目).类似的解释适用于奇数版本.

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.

注意 . 排除几个换行符: u2028u2029.对于包含此类字符的字符串,它会产生意想不到的结果.将 . 替换为 [sS](或其他等效结构),使其适用于所有情况.

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

出于实际目的,match 是完成这项工作的正确工具:

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 个字符:

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.

同上,您可能需要将 . 更改为 [sS] 以使其适用于所有情况.

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

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

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