Regular Expressions - how to replace a character within quotes

前端 未结 3 1686
执念已碎
执念已碎 2020-12-16 03:16

Hello regular expression experts,

There has never been a string manipulation problem I couldn\'t resolve with regular expressions until now, at least in an elegant m

3条回答
  •  感动是毒
    2020-12-16 03:32

    Regular expressions are not particularly good at matching balanced text (i.e. starting and ending quotes).

    A naïve approach would be to repeatedly apply something like this (until it no longer matched):

    s/(^[^"]*(?:"[^"]*"[^"]*)*?)"([^",]*),([^"]*)"/$1"$2_$3"/
    

    But that wouldn't work with escaped quotes. The best (i.e. simplest, most readable, and most maintanable) solution is to use a CSV file parser, go through all the field values one by one (replacing commas with underscores as you go), then write it back out to the file.

提交回复
热议问题