javascript - 正则表达式替代lookbehind

标签 javascript regex

我有以下文字:

asdfasdf added Big Box of Chocolate Bars x9, Bottle of Beer x10, Empty Blood Bag x4 to the trade.
asdfasdf added Grenade x8, Pepper Spray x7 to the trade.
tasdf added Jacket x6 to the trade.
aasdfa added Banana Orchid x5 to the trade.
asdfasdas added Single Red Rose x4 to the trade.
dgfhdfggg added Bunch of Flowers x3 to the trade.
asdfax2sdfas added Blood Bag : A+ x2 to the trade.
asdasdasd added Empty Blood Bag x1 to the trade.
Monkey Plushie x10, Leather Gloves x12, Monkey Plushie X321

我想捕获元素名称和数量,猴子毛绒x10单朵红玫瑰x4等。 目前我正在使用正向回顾来做到这一点,但似乎它在 react native 上不可用,所以我需要一个替代方案。到目前为止我得到的最好的是 (?:added)(\s.+x\d+) ...是的,我在正则表达式方面很糟糕...

最佳答案

按换行符分割,然后匹配该行中的前两个单词,同时捕获该行的其余部分(除了 to the trade 部分,我们要排除该部分,因此通常匹配它) 。然后提取捕获的组并用逗号和空格分隔:

const input = `asdfasdf added Big Box of Chocolate Bars x9, Bottle of Beer x10, Empty Blood Bag x4 to the trade.
asdfasdf added Grenade x8, Pepper Spray x7 to the trade.
tasdf added Jacket x6 to the trade.
aasdfa added Banana Orchid x5 to the trade.
asdfasdas added Single Red Rose x4 to the trade.
dgfhdfggg added Bunch of Flowers x3 to the trade.
asdfax2sdfas added Blood Bag : A+ x2 to the trade.
asdasdasd added Empty Blood Bag x1 to the trade.`;
const output = input
  .split('\n')
  .flatMap(
    line => line
      .match(/\S+ \S+ (.*) to the trade\./)[1]
      .split(', ')
  );
console.log(output);

如果您无法使用 flatMap,请改为使用 concat:

const input = `asdfasdf added Big Box of Chocolate Bars x9, Bottle of Beer x10, Empty Blood Bag x4 to the trade.
asdfasdf added Grenade x8, Pepper Spray x7 to the trade.
tasdf added Jacket x6 to the trade.
aasdfa added Banana Orchid x5 to the trade.
asdfasdas added Single Red Rose x4 to the trade.
dgfhdfggg added Bunch of Flowers x3 to the trade.
asdfax2sdfas added Blood Bag : A+ x2 to the trade.
asdasdasd added Empty Blood Bag x1 to the trade.`;
const addedsArrOfArrs = input
  .split('\n')
  .map(
    line => line
      .match(/\S+ \S+ (.*) to the trade\./)[1]
      .split(', ')
  );
const output = [].concat(...addedsArrOfArrs);
console.log(output);

如果你根本无法使用Javascript字符串/数组操作,你可以使用正则表达式

\b(?!.*added)\w[^,\n]*(?=.*x\d)x\d+

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

但这很丑陋,而且很难一眼理解,所以我不推荐它。

关于javascript - 正则表达式替代lookbehind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58899172/

相关文章:

javascript - 在模型图像下方添加文本框

javascript - 在 Javascript 中查找没有 includes/indexOf/Regex 的字符串中的子字符串

python - 如何在 pandas df 上使用这个有效的正则表达式 (re) 来删除多余的非数字字符,星号 (*)?

python - Python 正则表达式的命名约定?

javascript - .map 不是函数

javascript - 如何在 html 搜索方法期间修复列大小?

python - 评估正则表达式上的字符串匹配的语法是什么?

regex - 在 ActionScript 中,如何使用 RegExp 类检查给定的正则表达式是否已编译

javascript - jQuery 就绪 - 如何剥离现有的就绪句柄?

javascript - 使用正则表达式搜索单词