开发者

Regex to strip some lines out of a text file

I need to try and strip out lines in a text file t开发者_运维技巧hat match a pattern something like this:

anything SEARCHTEXT;anything;anything

where SEARCHTEXT will always be a static value and each line ends with a line break. Any chance someone could help with the regext for this please? Or give me some ideas on where to start (been to many years since I looked at regex).

I am planning on using PHP's preg_replace() for this.

Thanks.


This solution removes all lines in $text which contain the sub-string SEARCHTEXT:

$text = preg_replace('/^.*?SEARCHTEXT.*\n?/m', '', $text);

My benchmark tests indicate that this solution is more than 10 times faster than '/\n?.*SEARCHTEXT.*$/m' (and this one correctly handles the case where the first line matches and the second one doesn't).


Use a regex to match the whole line like so:

^.*SEARCHTEXT.*$

preg_replace would be a good option for this.

$str = preg_replace('/\n?.*SEARCHTEXT.*$/m', '', $str);

The \n escape matches the line break for the matched line. This way matched lines are removed and the replace method does not just leave empty lines in the string.

The /m flag makes the caret (^) match the start of each line instead of the start of the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜