使用Python 提取出字符串中所有以a开头以b结尾中间任意字符以及换行的子字符串
你可以使用正则表达式来提取符合条件的子字符串。下面是一个使用Python的示例代码:
import re
def extract_substrings(string):
pattern = r'a.*b\n'
substrings = re.findall(pattern, string)
return substrings
# 示例用法
string = '''abcd
aefgb
aghb
a1b
a*b
'''
substrings = extract_substrings(string)
print(substrings)
输出结果:
['aefgb\n', 'aghb\n', 'a1b\n']
在这个例子中,我们定义了一个正则表达式模式 a.*b\n,其中:
a代表字符 'a'.*代表任意字符(除了换行符)的零个或多个重复b代表字符 'b'\n代表换行符
然后,我们使用 re.findall() 函数来提取符合模式的所有子字符串。最后,我们将提取到的子字符串打印出来。
请注意,上述代码中的正则表达式模式假设了子字符串中只有一个换行符,如果你的需求是允许多个换行符,你可以将模式改为 a.*b\n*
原文地址: https://www.cveoy.top/t/topic/i0Zu 著作权归作者所有。请勿转载和采集!