Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace enters between quotes

How do i replace all enters between two quotes in a text file. The first quote is always preceded by a tab or it is the first character in the row (csv file). I tried the following regex

/(\t"|^")([^"]*)(\n)([^"]*")/gm

but this regex only matches the first enter between two quotes, not all.

For example, the following text:

xx "xx 
xx 
xx" 
xx 
"xx"
xx 
xx
"xxx xxx 
xx"

should become

xx "xx xx xx" 
xx 
"xx"
xx 
xx
"xxx xxx xx"

I read the following post ( javascript regex replace spaces between brackets ) which is very similar, but the regex suggested there is not useable in my situation.

like image 581
Nebu Avatar asked Jun 07 '16 09:06

Nebu


2 Answers

With Javascript replace you can use a function as replacement.

var str = 'foo \n"a\n" bar\n';

str = str.replace(/"[^"]+"/g, function(m) {
 return m.replace(/\n/g, ' ');
});

console.log(str);

The regex "[^"]+" will match quoted stuff with one or more non-quotes in between.

Add conditions such as tab or start to the pattern as needed: (?:\t|^)"[^"]+"

like image 89
bobble bubble Avatar answered Nov 18 '22 20:11

bobble bubble


\n(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)

You can use this and replace by empty string.

See Demo

var re = /\n(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)/g; 
var str = 'xx "xx \nxx \nxx" \nxx \n"xx"\nxx \nxx\n"xxx xxx \nxx"';
var subst = ''; 

var result = str.replace(re, subst);
like image 2
vks Avatar answered Nov 18 '22 19:11

vks