简体   繁体   中英

RegEx alternative to lookbehind

I have the following text:

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

I want to capture the item names and the quantity, Monkey Plushie x10 , Single Red Rose x4 , etc. At the moment I am using positive lookbehind to do it but it seems that it's not available on react native so I need an alternative to it. Best I got so far is (?:added)(\s.+x\d+) ...yes I am terrible at regex...

Split by newlines, then match the first two words in the line, while capturing the rest of the line (except the to the trade part, which we want to exclude, so match it normally). Then extract the captured group and split by a comma and a space:

 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);

If you can't use flatMap , then spread into concat instead:

 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);

If you can't use Javascript string/array manipulation at all, you can use the regular expression

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

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

but that's ugly and a lot harder to understand at a glance, so I wouldn't recommend it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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