(?ui)在Python正则表达式中的含义是什么?

ala*_*lan 3 python regex

Python模糊Wuzzy库包括以下正则表达式:

regex = re.compile(r"(?ui)\W")
return regex.sub(u" ", a_string)
Run Code Online (Sandbox Code Playgroud)

(https://github.com/seatgeek/fuzzywuzzy/blob/master/fuzzywuzzy/string_processing.py#L17)

这将用空格替换a_string中的任何非字母数字.

(?ui)位做了什么?没有它似乎工作正常.

谢谢

jam*_*lak 5

http://docs.python.org/2/library/re.html#regular-expression-syntax

(?iLmsux)(集合中的一个或多个字母'i', 'L', 'm', 's', 'u', 'x'.)组匹配空字符串; 字母设置相应的标志:

  • re.I (忽略大小写),
  • re.L (依赖于语言环境),
  • re.M (多线),
  • re.S (点匹配所有),
  • re.U (取决于Unicode),
  • re.X (详细),

对于整个正则表达式.(标志在模块内容中描述.)如果您希望将标志包含在正则表达式的一部分中,而不是将标志参数传递给re.compile()函数,这将非常有用.

请注意,该(?x)标志更改了表达式的解析方式.它应该首先在表达式字符串中使用,或者在一个或多个空格字符之后使用.如果标志前面有非空白字符,则结果未定义.

tl; dr (?u)在正则表达式中使用unicode并(?i)忽略大小写


Ray*_*ger 5

üunicode的标志忽略大小写的标志.

unicode标志使\ w,\ W,\ b,\ B,\ d,\ D,\ s和\ S依赖于Unicode字符属性数据库.例如:

>>> re.findall(r'\d+', u'The answer is \u0664\u0662')         # No flag
[]

>>> re.findall(r'(?u)\d+', u'The answer is \u0664\u0662')     # With unicode flag
[u'\u0664\u0662']
Run Code Online (Sandbox Code Playgroud)

ignore case标志执行不区分大小写的匹配.表达式[A-Z]也会匹配小写字母.这不受当前区域设置的影响.例如:

>>> re.findall(r'[a-z]+', 'HELLO world')         # No flag
['world']

>>> re.findall(r'(?i)[a-z]+', 'HELLO world')     # With ignore case flag
['HELLO', 'world']
Run Code Online (Sandbox Code Playgroud)