简体   繁体   English

如何使用正则表达式在单引号之间查找双引号?

[英]how to find double quotes between single quotes using regex expression?

I have a string like "how "are" you", I want to replace quotes which are inside the quotes surrounding "are" with \" using regex in python我有一个字符串,如“你如何”,我想用 python 中的正则表达式将“是”周围的引号内的引号替换为 \”

input_file =  'D:/Extracts/yourFileName.csv'
file_output= 'D:/Extracts/yourFileName_out.csv'

with open(input_file, 'r',encoding="utf8") as f, open(file_output, 'w',encoding="utf8") as fo:
    for line in f:
        fo.write(line.replace('"', '\"').replace(""", ""))

I want the output like "how \"are\" you"我想要 output 像"how \"are\" you"

The strings '\"' and '"' are identical: they both are just a single double-quote, because the sequence \" encodes a double-quote character (usually for use in " -quoted strings).字符串'\"''"'是相同的:它们都只是一个双引号,因为序列\"编码了一个双引号字符(通常用于" -quoted 字符串)。

If you really want a backslash before the quote, you'll have to escape it:如果你真的想在引号前加一个反斜杠,你必须转义它:

fo.write(line.replace('"', '\\"'))

In order to not replace the first and last character, you can instead use regular expressions:为了不替换第一个和最后一个字符,您可以改用正则表达式:

fo.write(re.sub('(?<!^)"(?!$)', '\\"', line))

The regular expression consists of a negative lookbehind ( (?<!^) ; asserting that no line starts before the quote), the quote character itself, and a negative lookahead ( (?!$) ; asserting that no line ends after the quote).正则表达式由一个否定的lookbehind ( (?<!^) ; 断言没有行在引号之前开始)、引号字符本身和一个否定的lookahead ( (?!$) ; 断言没有行在引号之后结束)。

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Regex Expression可以获得双引号之间的所有内容 - Regex Expression to get everything between double quotes 使用正则表达式将 Python 中的转义双引号替换为单引号 - Replace escaped double quotes to single quotes in Python using regex 使用 python,如何将单引号替换为双引号 - Using python, How to replace single quotes to double quotes 正则表达式在每个单词的开头和结尾查找双引号或单引号 - regex find double or single quotes in start and end of each word 正则表达式:给定一个字符串,请在双引号中查找子字符串,而不在双引号中查找子字符串 - Regex: Given a string, find substring in double quotes and substring not in double quotes 正则表达式在单引号之间查找内容,但前提是包含某个单词 - Regex find content in between single quotes, but only if contains certain word 尝试使用正则表达式在python中的双引号内查找模式 - trying to find patterns within double quotes in python using regex 用双引号或单引号引起来的正则表达式字符串 - regex string enclosed by double quote or single quotes 在逻辑运算符表达式之间添加双引号 - Add double quotes between a logical operator expression 如何删除嵌套在其他双引号正则表达式中的双引号 - How to remove double quotes nested within other double quotes regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM