将字符串拆分为双重出现次数和单次出现的数字1

问题描述 投票:-4回答:1

如果角色1出现两次或一次,我正在尝试拆分字符串。另外,我只使用1s和2s。此外,订单必须取决于以下示例:

var str =“111221”;

我想要strArr = [“1”,“11”,“2”,“2”,“1”];

str.match(/ 1 {2} | 2 | 1 {1} / g)将返回['11','1','2','2','1']。但是,这不是正确的顺序。 ie)5 1''11111' - > ['1','11','11']和6 1s'111111' - > ['11','11','11']

javascript node.js regex string frontend
1个回答
0
投票

想出了这个。

(?:1(?=(?:11)*(?!1))|11|2)

它基本上只得到第一个奇数1,然后得到均匀。

https://regex101.com/r/UtbhsV/1

解释

 (?:
      1                   # First, try 1
      (?=                 # Must be followed by even amount of 1's
           (?: 11 )*
           (?! 1 )
      )
   |  11                  # Or, only even's left, just get 11
   |  2                   # Or, How about a  2 ?
 )
© www.soinside.com 2019 - 2024. All rights reserved.