正则表达式在python中的unicode单词/数字之间添加空格

问题描述

我尝试将基本的正则表达式用于 unicode,但我无法让它们处理包含传统 A-Z 和数字以外的字符的字符串

我正在查看不属于 A-Z 字母家族的多种语言的示例

text = "20किटल"
res = re.sub("^[^\W\d_]+$",lambda ele: " " + ele[0] + " ",text)

Output:
20किटल

第二次尝试:

regexp1 = re.compile('^[^\W\d_]+$',re.IGnorECASE | re.UNICODE)
regexp1.sub("^[^\W\d_]+$",text)

 Output:
 20किटल


Expected output:
**20 किटल**

解决方法

使用Pypi regex library

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import regex

text = "20किटल"
pat = regex.compile(r"(?<=\d)(?=\p{L})",re.UNICODE)
res = pat.sub(" ",text)
print res

其中 \p{L} 代表任何语言的任何字母

输出:

20 किटल
,

如果我正确理解您的要求,您会尝试以下操作吗:

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

import re

text = '20किटल'
print(re.sub(r'([0-9a-zA-Z_]+)([^\s0-9a-zA-Z_]+)',r'\1 \2',text))

输出:

20 किटल