簡體   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