Python 正则表达式:带有 re.ASCII 的模式仍然可以匹配 unicode 字符?

Python regex: pattern with re.ASCII can still match unicode characters?

我是 Python 正则表达式的新手,我正在尝试匹配 Python.

中的非白色 space ASCII 字符

以下是我的代码:

impore re

p = re.compile(r"[\S]{2,3}", re.ASCII)

p.search('1234')  # have some result

p.search('你好吗') # also have result, but Why?

我在re.compile中指定了ASCII模式,但p.search('你好吗')仍然有结果。我想知道我在这里做错了什么?

re.A标志只影响shorthand字符类匹配。

在Python3.x中,shorthand character classes are Unicode aware, the Python 2.x re.UNICODE/re.U默认为ON。即:

  • \d匹配任何Unicode十进制数字(即Unicode字符类别[Nd]中的任何字符)
  • \D匹配任何非十进制数字的字符。(因此,除Nd Unicode category中的字符外的所有字符)。
  • \w - 匹配Unicode字字符;这包括大多数可以作为任何语言单词一部分的字符,以及数字和下划线。(因此,\w+ 匹配 My name is Виктор 字符串中的每个单词)
  • \W - 匹配任何不是单词字符的字符。这与 \w. 相反(因此,它不会匹配任何 Unicode 字母或数字。)
  • \s - 匹配 Unicode whitespace 字符(它将匹配 NEL、hard spaces 等。 )
  • \S - 匹配任何不是白色的字符space。(因此,不匹配 NEL,hard space, 等等)
  • \b - 字边界匹配 Unicode letters/digits 和非 letters/digits 或 start/end 字符串之间的位置。
  • \B - 非字边界匹配两个 Unicode letters/digits 之间、两个非 letters/digits 或一个 Unicode non-letter/digit 和 start/end 之间的位置字符串.

如果你想禁用这个行为,你使用re.Are.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

这意味着:

  • \d = [0-9] - 不再匹配印地语、孟加拉语等数字
  • \D = [^0-9] - 并匹配 ASCII 数字以外的任何字符(即它现在充当 (?u)(?![0-9])\d
  • \w = [A-Za-z0-9_] - 现在它只匹配 ASCII 单词,Wiktor 匹配 \w+,但 Виктор 不匹配
  • \W = [^A-Za-z0-9_] - 它匹配除 ASCII letters/digits/_ 之外的任何字符(即它匹配 你好吗Виктор、等等
  • \s = [ \t\n\r\f\v] - 匹配常规 space、制表符、换行符、回车符 return、换页符和垂直制表符
  • \S = [^ \t\n\r\f\v] - 匹配除 space、制表符、换行符、回车符 return、换页符和垂直字符以外的任何字符选项卡,因此它匹配所有 Unicode 字母、数字和标点符号以及 Unicode(非 ASCII)白色 space。 例如,re.sub(r'\S+', r'{\g<0>}', '\xA0 ', flags=re.A) 将 return '{ } ',如您所见,\S 现在很难匹配 spaces.