如何使用RegExp遍历字符串并将其分段成数组?

问题描述 投票:0回答:1

我在Zapier中大量使用自定义JS代码。将数组导入此步骤后,Zapier会将其转换为文字字符串,即:

[['BigBoatBob,XL-1','LittleBoatMike,M-2','SunkBoatCheney,XS-9']

变成:

''BigBoatBob,XL-1,LittleBoatMike,M-2,SunkBoatCheney,XS-9'

我已经创建了一个函数来解析数组项(占文本逗号),但是看起来非常草率。任何人有任何建议来完善/缩短/使外观更专业吗?感谢您帮助我提高自己的能力:)

var array = splitArray('BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9');

function splitArray(x) {
  const pos = [];
  const POS = [];
  const res = [];
  for (var i = 0; i < x.length; i++) {
    if (x[i] == ',') pos.push(i);
  }
  for (i = 0; i < pos.length; i++) {
    let a = x.slice(pos[i]);
    if (!a.startsWith(', ')) POS.push(pos[i]);
  }
  POS.push(x.length);
  POS.unshift(0);
  for (i = 0; i < POS.length - 1; i++) {
      res.push(x.slice(POS[i], POS[i+1]));
  }
  return res.map(x => {
    if (x.startsWith(',')) {
      return x.slice(1);
    } else {
      return x;
    }
  });
}
console.log(array);
javascript regex iteration zapier
1个回答
0
投票

If您可以依靠逗号inwith字符串后的空格,并依靠它们的[[not是一个between字符串,可以将split与正则表达式/,(?! )/,它表示“逗号not后接空格:”

const str = 'BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9'; const array = str.split(/,(?! )/); console.log(array);
如果您

不能

依靠它,但是您可以依靠XL-1的格式等等,则可以使用exec循环(或使用最新的JavaScript引擎)或[matchAll)的polyfill:

const str = 'BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9'; const array = []; const rex = /(.*?,\s*[A-Z]{1,2}-\d)\s*,?/g; let match; while ((match = rex.exec(str)) !== null) { array.push(match[1]); } console.log(array);
正则表达式/(.*?,\s*[A-Z]{1,2}-\d)\s*,?/g表示:

    [.*?任意数量的任意字符,非贪婪
  • ,逗号
  • [\s*零个或多个空白字符
  • [[A-Z]{1,2}范围A-Z的一个或两个字母
  • -破折号
  • [\d一位数字(如果可以有多个,请使用\d+)]
  • 以上所有内容均在捕获组中
  • ,?后面的可选逗号

0
投票
我将使用Array.reduce:

var s = 'BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9' var result = s.split(',').reduce((acc, curr, i) => { if(i % 2 == 0) { acc[i] = curr } else { acc[i - 1] += curr } return acc }, []).filter(x => x) console.log(result)

0
投票
速记,

function splitIt(str) { return str.split(',').reduce((a,v,i)=>((i % 2 == 0)?a.push(v):a[a.length-1]=a[a.length-1]+","+v,a),[]); } // Example let str = `BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9`; console.log(splitIt(str));

© www.soinside.com 2019 - 2024. All rights reserved.