Luc
Luc

Reputation: 2805

Regex match pair query string

I have string like this:

prikey = 2, ju = 20150101, name = sdf, email = [email protected], sub = (한진해운) 2014년도 케미컬 선장, 1항기, 사 채용

I wanna split each pair like this:

  1. prikey=2

  2. ju=20150101

  3. name=sdf

  4. [email protected]

  5. sub=(한진해운) 2014년도 케미컬 선장, 1항기, 사 채용

I tried this code:

/((?:[^=,]+)=(?:[^=]+)),/g

But it doesn't work fine.

  1. prikey=2

  2. ju=20150101

  3. name=sdf

  4. [email protected]

  5. sub=(한진해운) 2014년도 케미컬 선장

Upvotes: 0

Views: 75

Answers (2)

l'L'l
l'L'l

Reputation: 47264

You'll likely be able to capture what you want with a pattern such as:

(?:,)\s|([^=]+=\s[\w@\.\s]+|[\w].+)

Result:

prikey = 2 
ju = 20150101 
name = sdf
email = [email protected]
sub = (한진해운) 2014년도 케미컬 선장, 1항기, 사 채용

Example:

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

Code:

http://jsfiddle.net/df06waLd/

Upvotes: 2

iplus26
iplus26

Reputation: 2647

You can just use str.split(', ')

var str = 'prikey = 2, ju = 20150101, name = sdf, email = [email protected], sub = (한진해운) 2014년도 케미컬 선장, 1항기, 사 채용';

var result = str.split(', ');
var wanted = [];

result.forEach(function(el) {
  if (el.indexOf('=') !== -1) {
    wanted.push(el);
  } else {
    wanted[wanted.length - 1] += ', ' + el;
  }
})

console.log(wanted);

And you will get:

["prikey = 2", "ju = 20150101", "name = sdf", "email = [email protected]", "sub = (한진해운) 2014년도 케미컬 선장, 1항기, 사 채용"]

Upvotes: 0

Related Questions