繁体   English   中英

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

[英]Regex to add space between unicode words/numbers in python

我尝试对 unicode 使用基本的正则表达式,但我无法让它们在包含传统 AZ 和数字以外的字符的字符串上工作

我正在查看不属于 AZ Alphabetical 家族的多种语言的示例

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_]+$", lambda ele: " " + ele[0] + " ", text)

 Output:
 20किटल


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

使用Pypi 正则表达式库

#!/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}代表任何语言的任何字母

Output:

20 किटल

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

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

import re

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

Output:

20 किटल

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM