把字符串分成字母和数字,保留符号

2024-10-06 07:52:22 发布

您现在位置:Python中文网/ 问答频道 /正文

给出下面的代码,来自this question的可接受答案:

import re    
pathD = "M30,50.1c0,0,25,100,42,75s10.3-63.2,36.1-44.5s33.5,48.9,33.5,48.9l24.5-26.3"    
print(re.findall(r'[A-Za-z]|-?\d+\.\d+|\d+',pathD))    
['M', '30', '50.1', 'c', '0', '0', '25', '100', '42', '75', 's', '10.3', '-63.2', '36.1', '-44.5', 's', '33.5', '48.9', '33.5', '48.9', 'l', '24.5', '-26.3']

如果我在pathD变量中包含诸如“$”或“£”之类的符号,re表达式会跳过它们,因为它的目标是[A-Za-z]和数字

^{pr2}$

我如何修改上面的regex模式,以便根据下面所需的输出保留非字母数字符号?

^{3}$

~~~

下面是相关的SO帖子,尽管我无法确切地找到如何在分割练习中保留符号:

Split string into letters and numbers

split character data into numbers and letters

Python regular expression split string into numbers and text/symbols

Python - Splitting numbers and letters into sub-strings with regular expression


Tags: and代码restring符号数字thissplit
1条回答
网友
1楼 · 发布于 2024-10-06 07:52:22

试试这个:

compiled = re.compile(r'[A-Za-z]+|-?\d+\.\d+|\d+|\W')
compiled.findall("$100.0thousand")
# ['$', '100.0', 'thousand']

这是高级版™ 在

^{pr2}$

区别在于:

compiled.findall("$$$-100thousand")  # ['$', '$', '$', '-', '100', 'thousand']
advanced_edition.findall("$$$-100thousand")  # ['$$$', '-100', 'thousand']

相关问题 更多 >