繁体   English   中英

Javascript:从字符串数组中删除括号中的单词和单词

[英]Javascript: Remove words and words in brackets from array of strings

我正在尝试从字符串中删除不必要的单词。 例如,“切碎”或删除括号中的单词,如“(可选)”。 我有删除测量值的代码,但我发现很难获得所需的输出。

输入:

const Input = [
   'chopped kale, or to taste',
   'lemon, juiced',
   'small yellow squash, diced (Optional)'
]

我只是想让正则表达式在一个叫做“品尝”和“切块”等不需要的词的数组中查找词并删除它们

期望输出:

const output = [
   'chopped kale',
   'lemon',
   'small yellow squash'
]

这是我的代码:

import {measures} from './measures'
const regXMeasureAndMatter = RegExp('^(?<left>[^¼½¾\\d]+)*(?<count>¼|½|¾|\\d+\\/\\d+|\\d+)\\s*(?<unit>' + measures.join('|') + ')*(?<right>.*)');

function rearrangeMeasureAndMatter(match, left, count, unit, right) {
  left = (left || '' ).trim();
  right = (right || '' ).trim();
  return [
  
    count,
    (unit || ''),
    [left, right].join((left && right) || '')

  ].join(' ')
}

export function arrangeIngri(str) {
  return str
    .replace(regXMeasureAndMatter, rearrangeMeasureAndMatter)
    .replace(/\s+/g, ' ').trim()
}

// get proper ingris

export function createUnitCentricCapturingRegX(unitList) {
  const options = unitList
    .map(unit => escapeRegExpSearchString(unit))
    .join('|')
    .replace((/\\\.\\s\+/g), '\\\.\\s*');

  return RegExp('^(?<amount>.*?\\s*\\b(?:' + options + '))\\b\\s*(?<value>.*)$', 'i');
}
export const unitlessCapturingRegX = (/^(?<amount>¼|½|¾|\d+\/\d+|\d+)\s*(?<value>.*)$/);


export function collectNamedCaptureGroupData(collector, item) {
  item = item.trim();

  const { regXPrimary, regXSecondary, defaultKey, list } = collector;
  const result = regXPrimary.exec(item) || regXSecondary.exec(item);

  list.push(
    (result && result.groups && Object.assign({}, result.groups))
    || { [defaultKey]: item }
  );
  return collector;
}

function escapeRegExpSearchString(text) {

  return text
    .replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&')
    .replace((/\s+/), '\\s+');
}
const splitMe = w => w.map(a => a.substr(0, a.lastIndexOf(",")))

const input = [
   'chopped kale, or to taste',
   'lemon, juiced',
   'small yellow squash, diced (Optional)'
]

代码按预期吐出

const output = [
   'chopped kale',
   'lemon',
   'small yellow squash'
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM