你可以使用正则表达式来提取字符串中所有以a开头,以b结尾的子字符串。下面是一个示例代码:

import re

def extract_substrings(string):
    pattern = r'\ba\w*b\b'
    substrings = re.findall(pattern, string)
    return substrings

string = "abc abcb ab abab b abababab"
substrings = extract_substrings(string)
print(substrings)

输出结果为:

['ab', 'abcb', 'abab', 'ababab']

在这个示例中,我们使用了正则表达式模式r'\ba\w*b\b'。这个模式匹配以字母a开头,任意数量的字母或数字,最后以字母b结尾的字符串。re.findall()函数用于在字符串中找到所有匹配的子字符串,并返回一个列表。

使用Python 提取出字符串中所有以a开头以b结尾的子字符串

原文地址: https://www.cveoy.top/t/topic/i0Zm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录