【问题标题】:python regex add space whenever a number is adjacent to a non-number每当数字与非数字相邻时,python 正则表达式都会添加空格
【发布时间】:2016-08-09 10:49:07
【问题描述】:

我正在尝试将非数字与 Python 字符串中的数字分开。数字可以包括浮点数。

示例

Original String               Desired String
'4x5x6'                       '4 x 5 x 6'
'7.2volt'                     '7.2 volt'
'60BTU'                       '60 BTU'
'20v'                         '20 v'
'4*5'                         '4 * 5'
'24in'                        '24 in'

这是一个关于如何在 PHP 中实现这一点的非常好的帖子:

Regex: Add space if letter is adjacent to a number

我想在 Python 中操作上面的字符串。

以下代码在第一个示例中有效,但在其他示例中无效:

new_element = []
result = [re.split(r'(\d+)', s) for s in (unit)]
for elements in result:
   for element in elements:
       if element != '':
           new_element.append(element)

    new_element = ' '.join(new_element)
    break

【问题讨论】:

  • 请发布您的尝试
  • 那么您是否尝试过该线程中的任何内容?我确信r'(?<=[a-zA-Z])(?=\d)|(?<=\d)(?=[a-zA-Z])' 非常接近。
  • 嗨,不幸的是 re.sub('/(?
  • 您不能将正则表达式对象传递给 re 方法,只能传递模式本身(请参阅上面的建议 - 这对您不起作用,但关闭)。
  • 你好。非常感谢, re.sub(r'(?

标签: python regex replace formatting alphanumeric


【解决方案1】:

简单!只需替换它并使用 Regex 变量。不要忘记去除空格。 请尝试以下代码:

import re
the_str = "4x5x6"
print re.sub(r"([0-9]+(\.[0-9]+)?)",r" \1 ", the_str).strip() // \1 refers to first variable in ()

【讨论】:

  • 这也会从字符串的任一端删除任何预先存在的空格。
  • 是的。但我认为他无论如何都不需要它。
  • 如果我有这样的“测试一个 1000I.U\10ML 测试”怎么办?
【解决方案2】:

我像你一样使用了拆分,但修改如下:

>>> tcs = ['123', 'abc', '4x5x6', '7.2volt', '60BTU', '20v', '4*5', '24in', 'google.com-1.2', '1.2.3']
>>> pattern = r'(-?[0-9]+\.?[0-9]*)'
>>> for test in tcs: print(repr(test), repr(' '.join(segment for segment in re.split(pattern, test) if segment)))
'123' '123'
'abc' 'abc'
'4x5x6' '4 x 5 x 6'
'7.2volt' '7.2 volt'
'60BTU' '60 BTU'
'20v' '20 v'
'4*5' '4 * 5'
'24in' '24 in'
'google.com-1.2' 'google.com -1.2'
'1.2.3' '1.2 . 3'

似乎有想要的行为。

请注意,在加入字符串之前,您必须从数组的开头/结尾删除空字符串。请参阅this question 了解说明。

【讨论】:

  • 这不适用于123www.google.com,因为非数字中间有.
猜你喜欢
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
  • 2021-06-10
相关资源
最近更新 更多