Python 使用unicode字符从字符串生成正则表达式

Python 使用unicode字符从字符串生成正则表达式,python,regex,Python,Regex,我有一个字符串: alphabet = unicode("abś", 'utf-8'); 如何将其转换为: "ab\\u015B"; ??我试过这个密码: al = "" for char in alphabet: if ord(char) > 127: al += "\\u" + format(ord(char), 'x') else: al += char 但当我想从中生成正则表达式时,它不能正确匹配字符: abc = re.compi

我有一个字符串:

alphabet = unicode("abś", 'utf-8');
如何将其转换为:

"ab\\u015B";
??我试过这个密码:

al = ""
for char in alphabet:
    if ord(char) > 127:
       al += "\\u" + format(ord(char), 'x')
    else:
       al += char
但当我想从中生成正则表达式时,它不能正确匹配字符:

abc = re.compile(u'[' + al + u']{1,}$', re.U).match
演示在这里:

我认为您可以在不转换原始unicode字符串的情况下得到您想要的:

>>> abc = re.compile(u"[abś]{1,}$", re.U).match
>>> abc(u"ś")
<_sre.SRE_Match object at 0x89f31a8>
>>> abc(u"ś").group()
u'\u015b'
>>> abc(u"a").group()
u'a'
>>> abc("x") is None
True
abc=re.compile(u“[abś]{1,}$”,re.u.match >>>abc(u“ś”) >>>abc(u“ś”).集团() u'\u015b' >>>abc(美国)集团() u'a' >>>abc(“x”)是无 真的
>>> abc = re.compile(u"[abś]{1,}$", re.U).match
>>> abc(u"ś")
<_sre.SRE_Match object at 0x89f31a8>
>>> abc(u"ś").group()
u'\u015b'
>>> abc(u"a").group()
u'a'
>>> abc("x") is None
True