【问题标题】:Split string into letters and numbers, keep symbols将字符串拆分为字母和数字,保留符号
【发布时间】:2019-05-26 21:55:56
【问题描述】:

鉴于下面的代码,来自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] 和数字为目标

[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 帖子,尽管我无法完全找到如何在拆分练习中保留符号:

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

【问题讨论】:

    标签: python regex


    【解决方案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']
    

    【讨论】:

    • 宾果游戏 - 接受。据我了解,\W 的目标到底是什么? (实际接受需要等待9分钟)
    • @Pythonic 任何不是“单词字符”的东西,大致相当于[^A-Za-z0-9_](注意下划线),
    • 完美,advanced_edition 做到了,因为您强调了在给定用例中,符号隐含地意味着与数字粘在一起
    • @PedroRodrigues 我批准了您的编辑建议并将其还原。这是因为你的建议是有效的和明智的,但我不喜欢它(所以我没有直接拒绝它)。还是谢谢你。
    • 只是简单的案例,不使用缩小的正则表达式。但是继续做你疯狂的事情。我出去了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    相关资源
    最近更新 更多