本文介绍了正则表达式:在数字后跟字母时添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一组数字之后,我想在字符串中添加一个空格.例如,以下字符串应在数字后添加一个空格:
Following a set of numbers I would like to add a space to the string. For instance, the following strings should add a space after a number:
Before After "0ABCD TECHNOLOGIES SERVICES" "0 ABCD TECHNOLOGIES SERVICES" "ABCD0 TECHNOLOGIES SERVICES" "ABCD 0 TECHNOLOGIES SERVICES" "ABCD 0TECHNOLOGIES SERVICES" "ABCD 0 TECHNOLOGIES SERVICES" "ABCD TECHNOLOGIES0 SERVICES" "ABCD TECHNOLOGIES 0 SERVICES" "ABCD TECHNOLOGIES 0SERVICES" "ABCD TECHNOLOGIES 0 SERVICES" "ABCD TECHNOLOGIES SERVICES0" "ABCD TECHNOLOGIES SERVICES 0"我一直试图通过以下方式在Python中处理正则表达式:
I have been trying to work on regex in Python as in the following way:
text= re.sub(r'([0-9]+)?([A-Za-z]+)?([0-9]+)?', r'\1 \2 \3', text, 0, re.IGNORECASE)在前面的代码中,我得到了不想要的空间,这些空间在影响其他正则表达式转换:
With the previous code I am getting undesired spaces which are affecting other regex transformation:
"0 abcd technologies services "如何在不添加不需要的空格的情况下在字符串中增加空格?
How can I get the addition of space in the string without adding undesired spaces?
感谢您的指导:)
推荐答案您可以使用
re.sub(r'(?<=\d)(?=[^\d\s])|(?<=[^\d\s])(?=\d)', ' ', text)请参见 regex演示.
模式详细信息
- (?<=\d)(?=[^\d\s])-数字与字符之间的位置,而不是数字和空格
- |-或
- (?<=[^\d\s])(?=\d)-除数字和空格与数字之间的字符之间的位置.
- (?<=\d)(?=[^\d\s]) - a location between a digit and a char other than a digit and whitespace
- | - or
- (?<=[^\d\s])(?=\d) - a location between a char other than a digit and whitespace and a digit.
Python测试:
import re tests = ['0ABCD TECHNOLOGIES SERVICES', 'ABCD0 TECHNOLOGIES SERVICES', 'ABCD 0TECHNOLOGIES SERVICES', 'ABCD TECHNOLOGIES0 SERVICES', 'ABCD TECHNOLOGIES 0SERVICES', 'ABCD TECHNOLOGIES SERVICES0'] rx = repile(r'(?<=\d)(?=[^\d\s])|(?<=[^\d\s])(?=\d)') for test in tests: print(rx.sub(' ', test))输出:
0 ABCD TECHNOLOGIES SERVICES ABCD 0 TECHNOLOGIES SERVICES ABCD 0 TECHNOLOGIES SERVICES ABCD TECHNOLOGIES 0 SERVICES ABCD TECHNOLOGIES 0 SERVICES ABCD TECHNOLOGIES SERVICES 0更多推荐
正则表达式:在数字后跟字母时添加空格
发布评论