gpt4 book ai didi

regex - 正则表达式-如何在引号中替换字符

转载 作者:行者123 更新时间:2023-12-04 05:21:24 24 4
gpt4 key购买 nike

您好正则表达式专家,

到目前为止,从未有过我无法使用正则表达式解决的字符串操作问题,至少以一种优雅的方式仅需一步即可解决。这是我正在使用的示例数据:

0,"section1","(7) Delivery of 'certificate' outside the United States prohibited. Since both section 339 of the 1940 statute, 68/ and section 341 of the present law are explicit in their statement that the certificate shall be furnished the citizen, only if such individual is at the time within the United States, it is clear that the document could not and cannot be delivered outside the United States.",http://www.google.com/

1,"section2",,http://www.google.com/

2,"section3",",,",http://www.google.com/



这是更大的CSV文件的一部分。使用一个优雅的正则表达式,我只想用下划线字符(_)替换双引号中出现的所有逗号。重要的是,正则表达式不要替换引号之外的任何逗号,因为这会弄乱CSV数据结构。

谢谢,
汤姆

--

澄清:

抱歉,我在未完全阐明我的情况的情况下发布了问题,所以让我总结如下:
  • 假定引号内的引号已被转义(由Excel保存的CSV文件中的引号内的引号由"""""等表示,因此可以方便地预先替换)。
  • 我正在JavaScript中工作。

  • 使用上面的示例文本,下面是运行正则表达式替换后的样子(总共应该有5个替换):

    0,"section1","(7) Delivery of 'certificate' outside the United States prohibited. Since both section 339 of the 1940 statute_ 68/ and section 341 of the present law are explicit in their statement that the certificate shall be furnished the citizen_ only if such individual is at the time within the United States_ it is clear that the document could not and cannot be delivered outside the United States.",http://www.google.com/

    1,"section2",,http://www.google.com/

    2,"section3","__",http://www.google.com/

    最佳答案

    我会为您提供帮助,但您必须保证不再使用“优雅”一词。最近工作太辛苦了,值得休息。 :P

    (?m),(?=[^"]*"(?:[^"\r\n]*"[^"]*")*[^"\r\n]*$)

    如果在逗号和记录的末尾之间有奇数个引号,则这与逗号匹配。我假设使用标准CSV格式,其中一条记录在不包含在引号中的下一行分隔符处结束。行引号在带引号的字段中是合法的,如果引号与另一个引号一起转义,则引号也是如此。

    根据您使用的正则表达式风格,您可能必须使用 \r?$而不是 $。例如,在.NET中,仅将换行符( \n)视为行分隔符。但是在Java中, $\r中的 \r\n之前匹配,但在 \r\n之间不匹配(除非您设置UNIX_LINES模式)。

    关于regex - 正则表达式-如何在引号中替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4476812/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com