Search code examples
regexmacostextmateregex-groupvcf-vcard

replace white space with commas in lines that can contain forward slashes and dashes


I am trying to replace white space in lines with text and forward slashes with commas without having a trailing comma on the end of the line.

I am using a text editor with separate find and replace strings.

the input looks like this (a few of the different variables):

CATEGORIES:ORION/AKC Collection accounts receivable White Plains 
CATEGORIES:ABITIBIBOWATER/NOA1 ENRON/NOA PAPERCO/CL DWA 
CATEGORIES:ONSITE FAO 
CATEGORIES:LAR-DAN Lar-Dan 

the results should be:

CATEGORIES:ORION/AKC,Collection,accounts,receivable,White,Plains 
CATEGORIES:ABITIBIBOWATER/NOA1,ENRON/NOA,PAPERCO/CL,DWA 
CATEGORIES:ONSITE,FAO 
CATEGORIES:LAR-DAN,Lar-Dan 

I tried:

CATEGORIES:([A-Z|a-z])*

but it only gets me the first expression

CATEGORIES:ORION (in the first example.

Solution

  • The regex your tried CATEGORIES:([A-Z|a-z])* Matches CATEGORIES: followed by a capturing group repeated zero or more times with the ranges a-z and A-Z and also a | because they are in a character class. That would for example also match CATEGORIES:ONSITE||

    what you might do is match CATEGORIES in a capturing group and use \G to get a iterative match where you capturing not a whitespace characters in the second capturing group followed by matching one or more times a space where the end of the string $ does not follow.

    (CATEGORIES:|\G(?!^))(\S+)[ ]+(?!$)

    Regex demo

    And replace with the 2 capturing groups followed by a comma

    $1$2,