-1

so i have a file of lines like so....

valueA +920.32 % valueA +479.89%
valueB +886.82 % valueB +424.59%
--- insert more similar lines ---

And I was using the following Regex to get only the two percents and store them in an array

myObject.valueA = text.match(/(?<=valueA)(?:.+?(?=%))/g);

resulting in which is what I desire

valueA: Array [ " +920.32 ", " +479.89" ]

I was very happy with that, and keep moving forward with my little project until I was trying to test it with my friend on an iPhone, and nothing happened. Which I have found out is due to safari not supporting positive look behinds so I have been looking for something to produced a similar result.

With a positive look ahead I got close but it included 'valueA ' in the result which i really don't want to have to remove with an extra line of code.

(?=valueA)(?:.+?(?=%))

Result

valueA: Array [ "valueA +920.32 ", "valueA +479.89" ]

I'm sure there's a simple way to do this, but I've been messing around on RegExr and had no luck. Thank you ahead of time.

Muamer Bektić
  • 299
  • 3
  • 16

2 Answers2

2

You can use this workaround using capture groups in matchAll method:

const s = `valueA +920.32 % valueA +479.89%
valueB +886.82 % valueB +424.59%`

var arr = [...s.matchAll(/\bvalueA\s+([^\s%]+)/g)]

arr.forEach(el => console.log( el[1] ))
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    almost perfect went from this... `myObject.valueA = text.match(/(?=valueA)(?:.+?(?=%))/g);` to this `myObject.valueA = [...text.matchAll(/\valueA\s+([^\s%]+)/g)]; myObject.valueA.forEach((el, i) => myObject.valueA[i]= el[1]);` Not one line anymore but better than my solution – Muamer Bektić Apr 28 '21 at 19:45
1

If thats really what the data looks like why not just capture +, ., and digits? ([\+\d\.]+)

const text = `valueA +920.32 % valueA +479.89%`;

console.log(text.match(/([\+\d\.]+)/g))
dave
  • 62,300
  • 5
  • 72
  • 93
  • because the data will have several lines with 32 possible values. not every value will be included and they may not always be in the right order, so I can't just assume that the first two numbers go to valueA – Muamer Bektić Apr 28 '21 at 18:34