Python正则表达式将字符串拆分为数字和文本/符号 [英] Python regular expression split string into numbers and text/symbols

查看:594
本文介绍了Python正则表达式将字符串拆分为数字和文本/符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串分成数字部分和文本/符号部分 我当前的代码不包含负数或小数,并且表现很奇怪,在输出的末尾添加了一个空列表元素

I would like to split a string into sections of numbers and sections of text/symbols my current code doesn't include negative numbers or decimals, and behaves weirdly, adding an empty list element on the end of the output

import re
mystring = 'AD%5(6ag 0.33--9.5'
newlist = re.split('([0-9]+)', mystring)
print (newlist)

当前输出:

['AD%', '5', '(', '6', 'ag ', '0', '.', '33', '--', '9', '.', '5', '']

所需的输出:

['AD%', '5', '(', '6', 'ag ', '0.33', '-', '-9.5']

推荐答案

您的问题与以下事实有关:您的正则表达式捕获一个或多个数字,并将它们添加到结果列表中,并且这些数字用作定界符,之前的部分和之后被考虑.因此,如果末尾有数字,则拆分会导致末尾的空字符串被添加到结果列表中.

Your issue is related to the fact that your regex captures one or more digits and adds them to the resulting list and digits are used as a delimiter, the parts before and after are considered. So if there are digits at the end, the split results in the empty string at the end to be added to the resulting list.

您可以使用正则表达式进行拆分,该正则表达式使用可选的负号匹配浮点数或整数,然后删除空值:

You may split with a regex that matches float or integer numbers with an optional minus sign and then remove empty values:

result = re.split(r'(-?\d*\.?\d+)', s)
result = filter(None, result)

要使负数/正数与指数匹配,请使用

To match negative/positive numbers with exponents, use

r'([+-]?\d*\.?\d+(?:[eE][-+]?\d+)?)'

-?\d*\.?\d+正则表达式匹配:

  • -?-可选的减号
  • \d*-0 +个数字
  • \.?-可选的文字点
  • \d+-一个或多个数字.
  • -? - an optional minus
  • \d* - 0+ digits
  • \.? - an optional literal dot
  • \d+ - one or more digits.

这篇关于Python正则表达式将字符串拆分为数字和文本/符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆