簡體   English   中英

Unicode正則表達式以匹配漢字字符類

[英]Unicode regex to match a character class of Chinese characters

^[一二三四五六七]、不匹配一、

但是^一、匹配一、

我指定漢字字符類的方式是否錯誤?

我從文件中讀取了正則表達式。

為我工作

>>> import re
>>> re.match(u'^[一二三四五六七]、', u'一、')
<_sre.SRE_Match object; span=(0, 2), match='一、'>
>>> re.match(u'^[一二三四五六七]、', u'一、').group(0)
'一、'

我認為您無法將正則表達式定義為unicode字符串。

在python3中,它將是

# -*- coding: utf-8 -*-

import re

with open('file') as f:
    reg = f.read().strip()
    print(re.match(reg, u'一、').group(0))

您需要確保使用正確的編碼讀取文件:

with open('my-regex-file', encoding='utf-8') as f:
    regex = re.compile(f.read())
with open('my-text-file', encoding='utf-8') as f:
    text = f.read()
if regex.match(text):
    print("It's a match!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM