正则表达式:在数字后跟字母时添加空格

编程入门 行业动态 更新时间:2024-10-28 18:23:47
本文介绍了正则表达式:在数字后跟字母时添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在一组数字之后,我想在字符串中添加一个空格.例如,以下字符串应在数字后添加一个空格:

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

更多推荐

正则表达式:在数字后跟字母时添加空格

本文发布于:2023-11-06 07:33:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563083.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后跟   空格   字母   数字   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!