python 正则表达式包含缺少的逗号

标签 python regex python-2.7

我需要确保字符串具有逗号分隔值。我读取的字符串可能有空格分隔的值。

  • 我的输入字符串中可能缺少一些逗号,也就是说,如果存在没有逗号的空格分隔值,我必须包含逗号
  • 我不应该对单引号或双引号内的字符串进行任何更改。这些带引号的值可以包含除引号之外的任何字母数字。

示例字符串是:

""" 1, ' unchanged 1' " unchanged  2 "  2.009, -2e15 """

我应该在“not this1”之后和“not this 2”之后添加逗号。

所以我的结果字符串应该是:

"""1,' unchanged 1'," unchanged 2 ",2.009,-2e15"""

我一直在尝试s1|s2|(s3)类型的正则表达式。但未能完成任务。

字符串可以有不同数量的值,以逗号分隔。

最佳答案

也许使用 findall、str.join 和 str.strip 会更容易,首先查找引号之间的字符串,然后查找所有非空白:

s = """ 1, ' unchanged 1' " unchanged  2 "  2.009, -2e15 3"""

r = re.compile("[\'\"].*?[\'\"]|\S+")
print(", ".join([x.strip(",") for x in r.findall(s)]))

1, ' unchanged 1', " unchanged  2 ", 2.009, -2e11, ' unchanged 1', " unchanged  2 ", 2.009, -2e15, 35, 3

如果您不想在逗号后有任何空格:

print(",".join([x.strip(",") for x in r.findall(s)]))
1,' unchanged 1'," unchanged  2 ",2.009,-2e15,3

关于python 正则表达式包含缺少的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30969459/

相关文章:

python , Pandas ;值错误 ('window must be an integer' ,)

python - 非交换符号化(或化简)

python - 插入新元素作为链表的头部 Python

python - 无法为 Python 3.4 创建工作虚拟环境

c# - 正则表达式 - 在范围内或零

javascript - 正则表达式中的美元符号 "\$",字边界为 "\b"(PHP/JavaScript)

python - 使用 Python 将 stdout 和 stderr 重定向到同一文件

python - wxPython "Library not loaded"

python - 彩色图像卷积核的 tensorflow 权重?

java - Java中以不同长度分割字符串