【问题标题】:Splitting a string on whitespace while ignoring specific whitespace在忽略特定空格的同时在空格上拆分字符串
【发布时间】:2016-10-16 13:51:33
【问题描述】:

我想在所有空格上拆分一个字符串,除了逗号前面的空格。

例子:

"abc de45+ Pas hfa, underak (333)"

将拆分为:

Item 1: abc
Item 2: de45+
Item 3: Pas
Item 4: hfa, underak
Item 5: (333)

【问题讨论】:

  • 欢迎来到 SO,由于 stackoverflow 不是代码编写服务,请通过添加您迄今为止尝试过的源代码来展示您的努力。

标签: python regex split


【解决方案1】:

你应该分开(?<!,)\s 在这里查看:https://regex101.com/r/9VXO49/1

【讨论】:

    【解决方案2】:

    如果你只想在一个空格处分割,那么只需使用split()

    a = "abc de45+ Pas hfa, underak (333)"
    split_str = a.split(' ')    #Splits only at space
    

    如果您想按照@Beloo 的建议在空格而不是句点处拆分,请使用正则表达式

    import re
    
    a = "abc de45+ Pas hfa, underak (333)"
    split_str = re.split(' ' , a)    #Splits just at spaces
    split_str = re.split('[ .:]', a)    #Splits at spaces, periods, and colons
    split_str = re.split('(?<!,)[ ]' , a)    #Splits at spaces, excluding commas
    

    您可能已经猜到了,如果您想排除某个字符,只需将其放在(?&lt;!) 之间即可

    【讨论】:

    • 你的正则表达式输出给出['abc de45+ Pas hfa, underak (333)']
    • @RS 不,现在它给了['abc', 'de45+', 'Pas', 'hfa,', 'underak', '(333)'] OP 特别提到他不想用逗号分开。
    • 啊感谢您指出。我以为他的意思只是逗号而不是逗号+空格。进行了更改。
    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    相关资源
    最近更新 更多