0

My input string looks like this:

&hello=HI1&op=1h23&hello=&op=&hello=HI3&op=&hello=HI4&op=OP4

If hello has text, I'd like the data to be captured. The op parameter is optional and may or may not have a value. In the string above, I would like the following output (each line will be stored as a separate value in an array):

hello=HI&op=1h23
hello=HI3&op=
hello=HI4&op=OP4

I've got it mostly working but the problem is if op has a value with any letters in the word 'hello', the remaining part of op won't be captured. As you can see in the sample string above, the first op value is 1h23, after the h, the values 23 isn't captured.

https://regex101.com/r/Er0kEo/2

I've tried:

/&hello=[A-z 0-9]+&op=[^&hello]*/gi

This mostly works, except if op has a value that contains any of the letters in the word 'hello'. I've also tried:

/&hello=[A-z 0-9]+&op=.+?(?=&hello)/gi

Only captures first input. Also tried (?!&hello) - slightly better but doesn't capture the last input. Tried with \b and didn't get very far, neither did ^&hello$.

I feel like I'm missing something small but 5 hours in, I'm beat.

greentea
  • 347
  • 1
  • 2
  • 12

3 Answers3

0

Using the regex /&(hello=\w*&op=\w*)/, will give the following required matches:

hello=HI&op=1h23
hello=HI3&op=
hello=HI4&op=OP4

JavaScript Demo

var pattern = /&(hello=\w*&op=\w*)/g;

var str = "&hello=HI1&op=1h23&hello=&op=&hello=HI3&op=&hello=HI4&op=OP4";

var result;

while (result = pattern.exec(str)) {
  console.log(result[1]);
}
Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
0

Try with the following regex ( using positive look-ahead ) :

hello=[a-z0-9]+&op=[^&]*

DEMO

JavaScript

var str = "&hello=HI1&op=1h23&hello=&op=&hello=HI3&op=&hello=HI4&op=OP4";
var result = str.match(/hello=[a-z0-9]+&op=[^&]*/gi);
console.log(result);
m87
  • 4,445
  • 3
  • 16
  • 31
  • [`[A-z]` matches more than letters](http://stackoverflow.com/a/29771926/3832970), but it is not so relevant here, I guess. What is relevant, is that OP expects to have the results without leading `&`. Also, `.*?(?=&|$)` is an "overkill" if you compare it with `[^&]*`. – Wiktor Stribiżew Mar 06 '17 at 10:12
  • When I do, I will for sure. – Wiktor Stribiżew Mar 06 '17 at 10:26
0
/hello=[a-z\s0-9]+&op=[a-z0-9]*/gi

Result

Match 1
Full match  1-18    `hello=HI1&op=1h23`
Match 2
Full match  30-43   `hello=HI3&op=`
Match 3
Full match  44-60   `hello=HI4&op=OP4`

https://regex101.com/r/Er0kEo/3

lkdhruw
  • 572
  • 1
  • 7
  • 22