多个换行符上的Python正则表达式 [英] Python regex over multiple newlines

查看:564
本文介绍了多个换行符上的Python正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个文件路径的字符串,其中一些路径中包含任意换行符,我想使用python解析该字符串,以便仅保留文件名和扩展名.

I have a string which contains multiple file paths, some of which contain arbitrary newlines within the path, and I want to parse the string using python so that only the filenames and extensions remain.

例如:

a/b/c/d/file1.c  
a/b/c/d/e/f/g/h/1/2/3/4/5/foo.c  
dir1/dir2/newlinedir  
/nextlinedir/bar.c

应进行解析以提供输出:

should be parsed to give output:

file1.c
foo.c
bar.c

file1.c
foo.c
bar.c

我正在使用以下正则表达式(文件名和扩展名的组必须分开以供以后使用):

I am using the following regular expression (the groups for the filename and extension must be separate for later purposes):

path_regex = re.compile(r'.*\/([^\/\.]*)(\.c){0,1}$', re.MULTILINE)
path_regex.sub(r'\g<1>\g<2>', input_string)

这将适用于具有单行路径的字符串,但不适用于包含换行符的路径. 我该怎么办?

This will work on strings with single line paths but not paths that contain newlines. What should I do?

推荐答案

^([\s\S]*?\/)(\w+\.c)

尝试一下.请参阅演示.这也将在multiline下工作.使用mmultiline标志.

Try this.See demo.This will work multiline too.Use m or multiline flag.

https://regex101.com/r/rX1tE6/7

这篇关于多个换行符上的Python正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆