1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Rep Power

    Replace spaces if between quotes

    Does anyone know if there's a way to do a regex replace where the spaces between quotes are changed to a ampersands?

    For example the first line to the second:
    here is "the text I" want "to change"
    here is "the&text&I" want "to&change"

    I am doing it in VBA but any example would be really helpful. Thanks in advance.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Paris area, France
    Rep Power
    You just cannot do that with a pure regex and, even with an extended regex package, it is at least very difficult and likely to be unreliable.

    You really need a parser to do this sort of things. See if you have a parsing library in VBA, or you can write a very simple parsing tool which could, for example, read characters one by one and set a flag to true when it meets the first quote and to false when it meets the next one (and so on). Then you do the replacements when he flag is true.

    Another way is to split the line on quotes into an array, make the changes in array elements that have an odd subscript, and then reconstruct the line. This is an example in Perl at the command line:
    Perl Code:
    $ perl -e '$c = qq/here is "the text I" want "to change"/;
    @a = split /"/, $c;
    for $i (0..$#a) {$a[$i] =~ s/ /&/g and $a[$i] = qq/"/ .  $a[$i] . qq/"/ if $i % 2;}
    print "@a";'
    here is  "the&text&I"  want  "to&change"

    The qq/.../ is just a way to quote text containing quotes. If it were not at the command line but in a program, the syntax would look simpler. It might look like this (untested):

    Perl Code:
    $c = 'here is "the text I" want "to change"';
    @a = split /"/, $c;
    for $i (0..$#a) {
         $a[$i] =~ s/ /&/g and $a[$i] = '"' .  $a[$i] . '"' if $i % 2;
    print "@a";

IMN logo majestic logo threadwatch logo seochat tools logo