代码之家  ›  专栏  ›  技术社区  ›  Lucas

如何在python中获得regex match的一部分作为变量?

  •  15
  • Lucas  · 技术社区  · 15 年前

    在Perl中,可以这样做(我希望语法正确…):

    $string =~ m/lalala(I want this part)lalala/;
    $whatIWant = $1;
    

    我想在python中做同样的操作,并将括号内的文本放入类似$1的字符串中。

    7 回复  |  直到 9 年前
        1
  •  17
  •   OJFord    10 年前

    参见: Python regex match objects

    >>> import re
    >>> p = re.compile("lalala(I want this part)lalala")
    >>> p.match("lalalaI want this partlalala").group(1)
    'I want this part'
    
        2
  •  22
  •   Nadia Alramli    15 年前

    如果要按名称获取部件,也可以执行以下操作:

    >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
    >>> m.groupdict()
    {'first_name': 'Malcom', 'last_name': 'Reynolds'}
    

    这个例子取自 re docs

        3
  •  11
  •   unutbu    12 年前
    import re
    astr = 'lalalabeeplalala'
    match = re.search('lalala(.*)lalala', astr)
    whatIWant = match.group(1) if match else None
    print(whatIWant)
    

    小提示:在Perl中,当您编写

    $string =~ m/lalala(.*)lalala/;
    

    regexp可以匹配字符串中的任何位置。等价物是用 re.search() 函数,而不是 re.match() 函数,它要求模式匹配从字符串的开头开始。

        4
  •  4
  •   Roger Pate    15 年前
    import re
    data = "some input data"
    m = re.search("some (input) data", data)
    if m: # "if match was successful" / "if matched"
      print m.group(1)
    

    检查 docs 更多。

        5
  •  2
  •   ghostdog74    15 年前

    不需要regex。想想简单。

    >>> "lalala(I want this part)lalala".split("lalala")
    ['', '(I want this part)', '']
    >>> "lalala(I want this part)lalala".split("lalala")[1]
    '(I want this part)'
    >>>
    
        6
  •  1
  •   Mark Byers    15 年前
    import re
    match = re.match('lalala(I want this part)lalala', 'lalalaI want this partlalala')
    print match.group(1)
    
        7
  •  0
  •   ansebbian0    9 年前
    import re
    
    string_to_check = "other_text...lalalaI want this partlalala...other_text"
    
    p = re.compile("lalala(I want this part)lalala")    # regex pattern
    m = p.search(string_to_check)                       # use p.match if what you want is always at beginning of string
    
    if m:
        print m.group(1)
    

    在尝试将Perl程序转换为用模块解析函数名的Python时,我遇到了这个问题,我收到一个错误,说“group”未定义。我很快意识到这个例外是因为P。 比赛 /P. 搜索 如果没有匹配的字符串,则返回0。

    因此,Group运算符不能对其执行操作。因此,为了避免出现异常,请检查是否存储了匹配项,然后应用group运算符。

    import re
    
    filename = './file_to_parse.py'
    
    p = re.compile('def (\w*)')            # \w* greedily matches [a-zA-Z0-9_] character set
    
    
    for each_line in open(filename,'r'):
        m = p.match(each_line)             # tries to match regex rule in p
        if m:
            m = m.group(1)
            print m