【问题标题】:What does re.match('(...),..', string) return?re.match('(...),..', string) 返回什么?
【发布时间】:2014-07-29 16:36:10
【问题描述】:

我是 python 新手,有点困惑:

type = order_change_separate_t

re.match('(...)..', type).group(1) 会返回什么?它会返回 order_change_separate 吗?

提前致谢!

【问题讨论】:

  • 你为什么不试试呢?
  • 我想了解 (...).. 背后的逻辑。它是否匹配到 _t 的模式,因为括号外只有 2 个点?

标签: python regex match


【解决方案1】:

你应该使用 python 的交互式 shell 来尝试这些东西:

sgupta-3:~ sgupta$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> type = "order_change_separate_t"
>>> import re
>>> print re.match('(...)..', type).group(1)
ord

它打印'ord'

(...) 是捕获组定义的组1,3个点匹配ord。

print re.match('(.*)..', type).group(1)

将返回“order_change_separate”

上面显然是一种非常粗略且不可扩展的提取方式,因为它仅适用于 'order_change_separate' 后跟正好 2 个字符。

更好的方法是像上面提到的用户'aelor',使用量词。

【讨论】:

    【解决方案2】:

    它将返回ord

    因为capture group () 里面只有三个字符

    如果你想order_change_separate 使用这个:

    re.match('(.*?)_.$', type).group(1)
    

    这将匹配最后一个underscore followed by a character之前的所有内容

    【讨论】:

      猜你喜欢
      • 2016-07-07
      • 1970-01-01
      • 2021-11-07
      • 2019-10-12
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 2013-02-26
      相关资源
      最近更新 更多