要保留一个或多个前导下划线的正则表达式,可以使用以下代码示例中的方法:
import re
pattern = r'^_+' # 匹配一个或多个前导下划线
string = '_test' # 要匹配的字符串
matches = re.findall(pattern, string) # 查找匹配的部分
if matches:
for match in matches:
print(match) # 输出匹配的部分
else:
print("No matches found.")
在上述示例中,使用了re.findall()
函数来查找匹配的部分,使用了^_+
作为正则表达式模式。^
表示匹配字符串的开头,_
表示匹配下划线,+
表示匹配一个或多个前导下划线。如果找到匹配的部分,则使用循环打印出来。如果没有找到匹配的部分,则输出"No matches found."。
可以根据需要修改string
变量的值来测试不同的字符串。