在正则表达式中容纳两种类型的引号 [英] Accommodate two types of quotes in a regex

查看:106
本文介绍了在正则表达式中容纳两种类型的引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正则表达式替换输入字符串中的引号。我的数据包含两种类型的引号-

I am using a regex to replace quotes within in an input string. My data contains two 'types' of quotes -

" and "

两者之间有非常细微的差别,目前,我在正则表达式中明确提到了这两种类型

There's a very subtle difference between the two. Currently, I am explicitly mentioning both these types in my regex

\"*\"*

我是尽管担心在将来的数据中我可能会得到不同的类型报价,而我的正则表达式可能会失败。存在多少种不同类型的报价?有没有办法将它们标准化为一种类型,以便我的正则表达式不会破坏看不见的数据?

I am afraid though that in future data I may get a different 'type' of quote on which my regex may fail. How many different types of quotes exist? Is there way to normalize these to just one type so that my regex won't break for unseen data?

编辑-

我的输入数据由HTML文件组成,我将HTML实体和URL转义为ASCII

My input data consists of HTML files and I am escaping HTML entities and URLs to ASCII

escaped_line = HTMLParser.HTMLParser().unescape(urllib.unquote(line.decode('ascii','ignore')))

其中,行指定HTML文件中的每一行。我需要忽略 ASCII,因为数据库中的所有文件都没有相同的编码,并且在读取文件之前我不知道编码。

where line specifies each line in the HTML file. I need to 'ignore' the ASCII as all files in my database don't have the same encoding and I don't know the encoding prior to reading the file.

Edit2

我无法使用替换功能来做到这一点。我尝试了replace('''',''),但它不会替换其他类型的引号''。如果我将其添加到另一个替换函数中,则会抛出非ASCII字符错误。

I am unable to do so using replace function. I tried replace('"','') but it doesn't replace the other type of quote '"'. If I add it in another replace function it throws me NON-ASCII character error.

条件

不允许使用外部库,只能使用本机python库。

No external libraries allowed, only native python libraries could be used.

推荐答案

发现有一种更简单的方法,只需在使用python编写的正则表达式前附加文字 u即可。

Turns out there's a much easier way to do this. Just append the literal 'u' in front of your regex you write in python.

regexp = ru'\"*\"*'

当您想将正则表达式编译/搜索/匹配到字符串时,请确保使用re.UNICODE标志。

Make sure you use the re.UNICODE flag when you want to compile/search/match your regex to your string.

re.findall(regexp, string, re.UNICODE)

不要忘记包含

#!/usr/bin/python
# -*- coding:utf-8 -*-

在源文件的开头,以确保可以使用unicode字符串写在您的源文件中。

at the start of the source file to make sure unicode strings can be written in your source file.

这篇关于在正则表达式中容纳两种类型的引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆