Sunday, 15 January 2012

perl - How to exclude regex text between two matches? -



perl - How to exclude regex text between two matches? -

i have set specific repeating text blocks. have dynamic file name, , dynamic message. every filename want extract message.

filename: dynamicfile.txt property: property neglect message: message want time: dynamictime

i want extract part after message, be: the message want.

what have: next match between filename , time.

(?<=filename: %myfilevar%)(?s)(.*)(?=time:)

whereas %myfilevar% dynamic file variables feed look with.

now need find way ommit after filename until message part. here have ommit:

property: property neglect message:

how done?

use warnings; utilize strict; $text; { local $/; $text = <data>; } $myfilevar = 'dynamicfile.txt'; if ($text =~ /filename: \q$myfilevar\e.*?message: (.*?)\s*time:/s) { print $1; } __data__ filename: dynamicfile.txt property: property neglect message: message want time: dynamictime

note: assumes time: comes right after message line. if not true, ikegami's solution offers way skip other lines.

explanation:

you can insert variable pattern, , interpolated. however, if variable contains special regex characters, treated regex characters. need surround variable \q...\e, create in between treated literally. if did not that, dot in filename match character. you don't need utilize lookarounds capture part of string. instead, utilize capture group--any normal sets of parentheses within pattern automatically set variables $1, $2, etc. for simple case this, improve enable single line mode (s) switch after pattern. (/s instead of (?s)). turning on within pattern experimental , should used if need apply part of pattern. .*? should used instead of .*. otherwise pattern match first message: lastly time: in file.

regex perl batch-file

No comments:

Post a Comment