Python 带有转义符、引号和定界符的正则表达式

Python Regular Expression with escape, quote, and delimiter characters

我是 python 的新手,正在尝试使用正则表达式或 CSV reader.

解决以下问题

我的输入字符串格式如下:

"some text"|"sample\" name|place\""|"some other text\""

预期输出为:

'some text','sample" name|place\"','some other text\"'

我的字符串有分隔符、转义字符和引号字符。当我将输入文本保存在文件中并使用 csv reader 读取它时,它按预期工作。

with open('inputfile.csv') as csvfile:
    inputValue = csv.reader(csvfile, delimiter='|', quotechar='"',escapechar = '\')
    for eachVal in inputValue:
        print(','.join(eachVal))

但是当我将输入值放入列表并使用 CSV reader 时,它没有给出正确的输出。

inputText = '"some text"|"sample\" name|place\""|"some other text\""'
inputValue = csv.reader(inputText, delimiter='|',quotechar='"', escapechar = '\')
for eachVal in inputValue:
    print(','.join(eachVal))  

任何有关此 CSV reader 的帮助或任何有关正则表达式的解决方案都会很棒。谢谢。

当您从文件中读取字符串时,您正在读取 "raw" 文本,这意味着 Python 不对反斜杠字符等提供特殊处理。要获得相同的处理代码中的字符串文字,您应该在字符串前加上 'r' (对于原始)。例如:

inputText = r'"some text"|"sample\" name|place\""|"some other text\""'