tags:

views:

259

answers:

2

I have a comma separated list of strings like the one below.

a,b   ,c ,d, ,      , , ,e, f,g,h  .

I want to write a regular expression that will replace the empty values i.e., strings that contain only white spaces to 'NA'. So the result should be

a,b   ,c ,d,NA,NA,NA,NA,e, f,g,h  .

I tried using ",\s+," to search but it skips the alternate empty strings and results in

a,b   ,c ,d,NA,      ,NA, ,e, f,g,h  .

What's the correct regex to use here ?

+5  A: 

(?<=,)\s+(?=,)

This is a lookbehind for a comma, then whitespace, then a lookahead for a comma

Greg
A: 

Here you are:

echo a,b ,c ,d, , , , ,e, f,g,h . | perl -p -e 's/, +[^a-z|A-Z]/,Na/g'

Or:

echo a,b ,c ,d, , , , ,e, f,g,h . | perl -p -e 's/, +\S/,Na/g'

if you want to make it work with non a-Z characters also (thanks for the comment :)

MrM
Nope. You assume all characters would fall into the [a-z] range.
Tomalak