【问题标题】:Need RegEx for replacing all commas outside of double quotes and replaceing with | - in python需要正则表达式来替换双引号之外的所有逗号并替换为 | - 在蟒蛇
【发布时间】:2021-09-22 12:12:39
【问题描述】:

我有这样的字符串:

8/30/2021 19:22,server1,app1,"user1, Mrs. user2",US,One,Email, Sent,Success

预期输出:

8/30/2021 19:22|server1|app1|user1, Mrs. user2|US|One|Email| Sent|Success

我的代码如下:

....
line = line.replace(',', '|')
print (line)

如何使用 RegEx 在 python 中处理双引号?

【问题讨论】:

  • 如果是 csv 文件,我建议使用 csv 模块为您完成。例如。 pandas.read_csv(file_name).to_csv(sep="|")

标签: python python-3.x python-2.7


【解决方案1】:

对不起,我的回答只是一个 hack,但可以达到预期的结果:

from io import StringIO
import pandas as pd

s = '8/30/2021 19:22,server1,app1,"user1, Mrs. user2",US,One,Email, Sent,Success'
print("|".join(pd.read_csv(StringIO(s)).columns))

输出:

'8/30/2021 19:22|server1|app1|user1, Mrs. user2|US|One|Email| Sent|Success'

我猜你可以通过谷歌搜索找到答案? :) 或者查看 pandas 库的源代码!

更新 - 是的,5 分钟的 Google Fu 揭晓答案!在这里:https://stackoverflow.com/a/632552/551694 请去投票。

re.sub('(,)(?=(?:[^"]|"[^"]*")*$)','|',s)

交付

'8/30/2021 19:22|server1|app1|"user1, Mrs. user2"|US|One|Email| Sent|Success'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-17
    • 2014-05-10
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2017-01-05
    相关资源
    最近更新 更多