将字符串拆分为字母和数字,保留符号

鉴于下面的代码,来自这个问题的公认答案:


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]和数字


[A-Za-z] # words

|

-?\d+\.\d+ # floating point numbers

|

\d+ # integers

如何根据下面的所需输出修改上面的正则表达式模式以保留非字母数字符号?


new_pathD = '$100.0thousand'


new_re_expression = ???


print(re.findall(new_re_expression, new_pathD))


['$', '100.0', 'thousand']


隔江千里
浏览 206回答 1
1回答

波斯汪

尝试这个:compiled = re.compile(r'[A-Za-z]+|-?\d+\.\d+|\d+|\W')compiled.findall("$100.0thousand")# ['$', '100.0', 'thousand']这是高级版™advanced_edition = re.compile(r'[A-Za-z]+|-?\d+(?:\.\d+)?|(?:[^\w-]+|-(?!\d))+')区别在于:compiled.findall("$$$-100thousand")  # ['$', '$', '$', '-', '100', 'thousand']advanced_edition.findall("$$$-100thousand")  # ['$$$', '-100', 'thousand']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python