Skip to content

Instantly share code, notes, and snippets.

@kshenoy
Created April 11, 2013 21:59
Show Gist options
  • Select an option

  • Save kshenoy/5367553 to your computer and use it in GitHub Desktop.

Select an option

Save kshenoy/5367553 to your computer and use it in GitHub Desktop.
Vim Regular Expression demonstrating use of look-ahead zero-width assertion to replace all the commas on a line that aren't a part of a quoted string
This uses positive look-ahead to check if there's a string ahead to substitute commas present outside quoted strings.
s/\v,(([^"]*"[^"]*")*[^"]*$)@=/|/g
Explanation:
* "[^"]*"
Match a double-quoted string
* [^"]*"[^"]*"
Match some characters along with the previous string
* ([^"]*"[^"]*")*
Check for the previous match 0 or more times
* ([^"]*"[^"]*")*[^"]*$
From a certain position ( a comma in this case ) check that we get some characters which aren't part of a string, a string, followed by some more non-string characters till the end of the line.
* (([^"]*"[^"]*")*[^"]*$)@=
Converts the previous match to a [look-ahead zero-width assertion](http://perldoc.perl.org/perlretut.html#Looking-ahead-and-looking-behind) and its (Vim counterpart](http://vimdoc.sourceforge.net/htmldoc/pattern.html#/zero-width)
Note:
* Deciding if a comma is inside or outside a string is done by checking the number of quotes ahead. If there are even number of quotes then we say that we're not inside a string.
* This does not handle cases like "abcd\"efghi" where the quote character is also a part of the string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment