【问题标题】:how to properly use a unicode string in python regex如何在 python 正则表达式中正确使用 unicode 字符串
【发布时间】:2016-09-26 09:16:46
【问题描述】:

我从用户那里得到一个输入正则表达式,它被保存为一个 unicode 字符串。在将输入字符串编译为正则表达式对象之前,我是否必须将其转换为原始字符串?还是没有必要?我是否将其正确转换为原始字符串?

import re
input_regex_as_unicode = u"^(.){1,36}$"
string_to_check = "342342dedsfs"

# leave as unicode
compiled_regex = re.compile(input_regex_as_unicode)
match_string = re.match(compiled_regex, string_to_check)

# convert to raw
compiled_regex = re.compile(r'' + input_regex_as_unicode)
match_string = re.match(compiled_regex, string_to_check)

@Ahsanul Haque,我的问题是更具体的正则表达式,正则表达式在将其转换为正则表达式对象时是否正确处理 unicode 字符串

【问题讨论】:

标签: python regex python-2.7


【解决方案1】:

re 模块可以正确处理 unicode 字符串和普通字符串,您不需要将它们转换为任何内容(但您应该在使用字符串时保持一致)。

没有像“原始字符串”这样的东西。如果它可以帮助您处理包含反斜杠的字符串,您可以在代码中使用原始字符串表示法。例如,要匹配换行符,您可以使用 '\\n'u'\\n'r'\n'ur'\n'

您在示例中使用原始字符串表示法没有任何作用,因为 r'''' 评估为相同的字符串。

【讨论】:

    猜你喜欢
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2015-03-30
    • 1970-01-01
    • 2011-07-03
    • 2013-09-30
    • 1970-01-01
    相关资源
    最近更新 更多