【问题标题】:String Manipulation with Regular Expression specifically or statements使用正则表达式或语句进行字符串操作
【发布时间】:2014-05-28 22:42:14
【问题描述】:

我正在尝试从短语中解析出某些字符串。这是这句话: '1楼 2楼 3楼 4楼' 结束语应该是: '一楼','二楼','三楼','四楼'

我无法获取正则表达式的“1st”、“2nd”、“3rd”、“4th”部分。我知道我可以使用 4 个不同的 or 语句来做一个不太直观的版本,但我想知道我是否可以用一个来做。

'\dst\s\w+|\dnd\s\w+|\drd\s\w+|\dth\s\w+' - 这是我试图缩短的漫长道路

是否可以将 st、nd、rd 和 th 组合成一个语句而不重复格式化? 谢谢。

【问题讨论】:

  • 试试这个\d+[a-zA-Z]{2}\s\w+

标签: python regex string python-3.x


【解决方案1】:

Live demo

这是正则表达式:

(\d+(st|nd|rd|th)) \w+\b

【讨论】:

    【解决方案2】:

    另一种可能性:

    import re
    s = '1st Floor 2nd Floor 3rd Floor 4th Floor'
    s2 = re.findall(r'\w+ Floor', s)
    

    【讨论】:

      【解决方案3】:

      是的,您可以将 st、nd、rd 和 th 组合成一个语句,但看起来您正试图从这个正则表达式中获取一个列表。为什么不试试这样的re.split

      >>> import re
      >>> t = '1st Floor 2nd Floor 3rd Floor 4th Floor'
      >>> re.split(r'(?<=Floor)\s+', t)
      ['1st Floor', '2nd Floor', '3rd Floor', '4th Floor']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-01
        • 2011-12-20
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        相关资源
        最近更新 更多