Skip to main content
 首页 » 编程设计

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

2025年02月15日28lyj

我是 python 的新手,正在尝试使用正则表达式或 CSV 阅读器解决以下问题。

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

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

预期输出是:

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

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

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

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

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

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

请您参考如下方法:

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

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