如何指定一系列 unicode 字符 [英] How do I specify a range of unicode characters

查看:48
本文介绍了如何指定一系列 unicode 字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何指定从 ' '(空格)到 \u00D7FF 的 unicode 字符范围?

我有一个像 r'[\u0020-\u00D7FF]' 这样的正则表达式,它不会编译说这是一个错误的范围.我是 Unicode 正则表达式的新手,所以我以前没有遇到过这个问题.

有没有办法让这个编译或者我忘记或还没有学过的正则表达式?

解决方案

您的 unicode 范围的语法与您期望的不符.

  1. 原始 r'' 字符串可防止解析 \u 转义,而正则表达式引擎不会这样做.这个集合中唯一的范围是 [0-\]:

    <预><代码>>>>re.compile(r'[\u0020-\u00d7ff]', re.DEBUG)在文字 117文字 48文字 48字面值 50范围 (48, 117)文字 48文字 48文字 100文字 55文字 102文字 102

  2. 使其成为 Unicode 文字 导致 \u 在离开时解析单独的其他反斜杠(虽然这不是一个问题),但前导零把它搞砸了.语法为\uxxxx\Uxxxxxxxx,所以解析为"\u00d7,f,f".

    <预><代码>>>>re.compile(ur'[\u0020-\u00d7ff]', re.DEBUG)在范围 (32, 215)文字 102文字 102

  3. 删除前导零或切换到 \U0000d7ff 将修复它:

    <预><代码>>>>re.compile(ur'[\u0020-\ud7ff]', re.DEBUG)在范围 (32, 55295)

How do I specify a range of unicode characters from ' ' (space) to \u00D7FF?

I have a regular expression like r'[\u0020-\u00D7FF]' and it won't compile saying that it's a bad range. I am new to Unicode regular expressions so I haven't had this problem before.

Is there a way to make this compile or a regular expression that I'm forgetting or haven't learned yet?

解决方案

The syntax of your unicode range will not do what you expect.

  1. The raw r'' string prevents \u escapes from being parsed, and the regex engine will not do this. The only range in this set is [0-\]:

    >>> re.compile(r'[\u0020-\u00d7ff]', re.DEBUG)
    in
      literal 117
      literal 48
      literal 48
      literal 50
      range (48, 117)
      literal 48
      literal 48
      literal 100
      literal 55
      literal 102
      literal 102
    

  2. Making it a Unicode literal causes \u parsing while leaving other backslashes alone (although that’s not a concern here), but the leading zeroes are messing it up. The syntax is \uxxxx or \Uxxxxxxxx, so it’s parsed as "\u00d7, f, f".

    >>> re.compile(ur'[\u0020-\u00d7ff]', re.DEBUG)
    in
      range (32, 215)
      literal 102
      literal 102
    

  3. Removing the leading zeroes or switching to \U0000d7ff will fix it:

    >>> re.compile(ur'[\u0020-\ud7ff]', re.DEBUG)
    in
      range (32, 55295)
    

这篇关于如何指定一系列 unicode 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆