python - 将字符串拆分为字母和数字,保留符号
问题描述
鉴于下面的代码,来自这个问题的公认答案:
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']
~~~
下面的相关 SO 帖子,虽然我无法完全找到如何在拆分练习中保留符号:
解决方案
尝试这个:
compiled = re.compile(r'[A-Za-z]+|-?\d+\.\d+|\d+|\W')
compiled.findall("$100.0thousand")
# ['$', '100.0', 'thousand']
这是高级版™</p>
advanced_edition = re.compile(r'[A-Za-z]+|-?\d+(?:\.\d+)?|(?:[^\w-]+|-(?!\d))+')
区别在于:
compiled.findall("$$$-100thousand") # ['$', '$', '$', '-', '100', 'thousand']
advanced_edition.findall("$$$-100thousand") # ['$$$', '-100', 'thousand']
推荐阅读
- wpf - 在 LiveCharts 的工具提示上仅显示 LineSeries 标题
- java - 如何在不使用 head 的情况下打印链表的元素
- java - 获取错误值
我是这个Android编程的新手。这次我想从 MySQL 数据库中获取数据经纬度。我已经将 GPS 数据从 Arduino 发送到我的 MySQL 数据库,然后我想使用 Google Map API 在我的 android 应用程序中动态显示它。
这是我的
- android - 使用 --livereload 标志运行 ionic cordova 项目错误
- python - 如何动画 3D 线图?
- javascript - Chart.Js:如何在工具提示中显示标签
- r - 如何将日期格式转换为总天数?
- graph - 了解 Neo4j 算法回写选项
- javascript - DiscordJS - 从数组中嵌入随机图像
- r - 如何循环大数据帧并计算频率?