python re正则 提取匹配的第一组

 

# -*- coding: utf-8 -*-
#!/usr/bin/python
 
 
import re

text ='href="/wangyou/txt13863.html">《扬剑天穹》
' regex = r">《([^》]+)》<\/a><\/strong>
" result = re.search(regex, text, re.MULTILINE) group1 = result.group(1) print(group1) #group1 ='扬剑天穹'

 下面另一种写法

# -*- coding: utf-8 -*-
#!/usr/bin/python


import re
def get_re_group1(test_str,regex):
    '''
    返回正则匹配的第一组

    Parameters
    ----------
    test_str : TYPE
        DESCRIPTION.
    regex : TYPE
        DESCRIPTION.
    Returns
    -------
    None.
    '''
    
    result=''
    matches = re.finditer(regex, str(test_str), re.MULTILINE)
    
    for matchNum, match in enumerate(matches, start=1):
        
       # print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
        
        for groupNum in range(0, len(match.groups())):
            groupNum = groupNum + 1
            result = match.group(1)
           # print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
    # print(result)        
    return str(result)

text ='href="/wangyou/txt13863.html">《扬剑天穹》
' regex = r">《([^》]+)》<\/a><\/strong>
" group1 = get_re_group1(text,regex) print(group1) #group1 ='扬剑天穹'

 

你可能感兴趣的:(Python,正则表达式)