Regex: match line if previous line satisfies a criteria

≡放荡痞女 提交于 2019-12-11 14:52:55

问题


What's a regex that will match lines whose previous line starts with a set of characters?

I'm trying to parse M3U files, and I need to match the lines whose preceding line starts with #EXTINF: So if we take this example:

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXTINF:11.54
ASMIK_tid_0000250058_m.600000-00000.ts
#EXTINF:8.51
ASMIK_tid_0000250058_m.600000-00001.ts
#EXTINF:11.76
ASMIK_tid_0000250058_m.600000-00002.ts
#EXTINF:10.05
ASMIK_tid_0000250058_m.600000-00003.ts
etc...

I only want to extract these lines:

ASMIK_tid_0000250058_m.600000-00000.ts
ASMIK_tid_0000250058_m.600000-00001.ts
ASMIK_tid_0000250058_m.600000-00002.ts
ASMIK_tid_0000250058_m.600000-00003.ts

I've tried variations on this answer and this: (?#EXT.*\n) but had no luck...


回答1:


Firstly you have to be sure that the function you are using is matching the whole file instead of line by line, otherwise this is impossible.

Then you would need to specify a lookbehind:

(?<=#EXTINF.*\r\n).*

If your regex implementation does not support lookbehinds OR repetition inside of a lookbehind, you can use two capture groups instead:

(#EXTINF.*\r\n)(.*)

Obviously you would simply ignore the first capture group, but keep all of the data in the second capture group.

If you need to manually specify that the . does not match newlines, you can specify the mode at the beginning of the regex: (?-s)



来源:https://stackoverflow.com/questions/20633416/regex-match-line-if-previous-line-satisfies-a-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!