Jean-philippe Emond
Jean-philippe Emond

Reputation: 1614

Javascript Split regex escaped delimiter

I'M trying to split a value only if the delimiter is not escaped.

I have read many question on StackOverflow on this but nothing works for me.

I have this value:

 InvalidMsg(this,'error with this caracter \', please change your value.');

the keyword here is: \'

I want to get the error message so I try something like:

var str = "InvalidMsg(this,'error with this caracter \', please change your value.');";
matches = str.match(/([^']|\\')+/g);
alert(matches[1]); //error with this caracter

I need to get the full message..

the full message is:

 error with this caracter ', please change your value

any idea?

thank you

Upvotes: 0

Views: 344

Answers (2)

anubhava
anubhava

Reputation: 784998

Following regex should work for you to capture your string from ' to ' ignoring all escaped quotes on the way:

/'((?:[^\\]*\\')*[^']*)'/

Online regex Demo

Upvotes: 1

Braj
Braj

Reputation: 46841

Try below regex and find the result in the matched groups using Non-capturing group

(.*)(?:,')(.*)\\('.*)(?:'\);)

Online demo

Input:

InvalidMsg(this,'error with this caracter \', please change your value.');

Match

  1. InvalidMsg(this
  2. error with this caracter
  3. ', please change your value.

Sample code:

var re = /(.*)(?:,')(.*)\\('.*)(?:'\);)/g;
var str = 'InvalidMsg(this,\'error with this caracter \', please change your value.\');';
var subst = '$2$3';

var result = str.replace(re, subst);

output:

error with this caracter ', please change your value.

Upvotes: 1

Related Questions