正则表达式不匹配。

3
我正在编写一个小的Python脚本从数据库中收集一些数据,唯一的问题是当我从mysql导出数据为XML文件时,它会在XML文件中包含一个\b字符。我编写了代码将其删除,但后来意识到我不需要每次都这样处理,因此我将其放入一个方法中,并在遇到\b时调用它,但现在正则表达式无法匹配,尽管我知道有\b存在。
以下是我的做法:
主程序:
'''Program should start here'''
#test the file to see if processing is needed before parsing
for line in xml_file:
    p = re.compile("\b")
    if(p.match(line)):
        print p.match(line)
        processing = True
        break #only one match needed

if(processing):
    print "preprocess"
    preprocess(xml_file)

预处理方法:

def preprocess(file):
    #exporting from MySQL query browser adds a weird
    #character to the result set, remove it
    #so the XML parser can read the data
    print "in preprocess"
    lines = []
    for line in xml_file:
        lines.append(re.sub("\b", "", line))

    #go to the beginning of the file
    xml_file.seek(0);
    #overwrite with correct data
    for line in lines:
        xml_file.write(line);
    xml_file.truncate()

任何帮助都将不胜感激, 谢谢。

小细节:在Python中不需要写if(x):,惯用的写法只是if x: - unwind
我是一名Java程序员,所以我想这是老习惯了,不过还是谢谢你的提示。 - Hunter McMillen
你是指字符串\b(两个字符)吗? - Qtax
在Python中,字符串中的\b表示退格符。 - Hunter McMillen
3个回答

7

\b正则表达式引擎的标志:

匹配空字符串,但仅在单词的开头或结尾。单词被定义为字母数字或下划线字符的序列,因此单词的结尾由空格或非字母数字、非下划线字符表示。请注意,\b被定义为\w和\W之间的边界,因此被认为是字母数字的确切字符集取决于UNICODE和LOCALE标志的值。在字符范围内,\b代表退格字符,以与Python的字符串文字兼容。

因此,您需要转义它才能使用正则表达式找到它。


1

在正则表达式中需要使用反斜杠进行转义。由于在 Python 中反斜杠同样需要被转义(除非您使用原始字符串,但您可能不想这么做),所以您需要总共使用3个反斜杠:

p = re.compile("\\\b")

这将生成一个匹配 \b 字符的模式。


0

如果我错了,请纠正我,但是为了替换'\b',没有必要使用regEx,你可以直接使用replace方法来实现:

def preprocess(file):
    #exporting from MySQL query browser adds a weird
    #character to the result set, remove it
    #so the XML parser can read the data
    print "in preprocess"
    lines = map(lambda line: line.replace("\b", ""), xml_file)
    #go to the beginning of the file
    xml_file.seek(0)
    #overwrite with correct data
    for line in lines:
        xml_file.write(line)
    # OR: xml_file.writelines(lines)
    xml_file.truncate()

请注意,在Python中不需要在字符串末尾使用“;”。

谢谢您的评论,正如我之前所提到的,我习惯用Java编程,习惯让我一直使用它。此外,我以前从未在Python中看到过Lambda表达式,感谢您的示例。 - Hunter McMillen
我现在似乎删除了我的xml文件的顶部部分,不确定原因,但我会为此开启另一个线程。 - Hunter McMillen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接