[英]Need a fairly complex regex for a simple text document
我更喜歡使用php或perl的答案,因為我可以隨意使用
該文件的格式如下:
Name : ...
INSERT INTO (...) Values (...)
Name : ... <--- These are the lines I need
INSERT INTO (...) Values (...) <---
<span style='color:red;'>FAILED to INSERT ...</span>
Name : ...
INSERT INTO (...) Values (...)
...
“FAILED to INSERT”范圍后面的行是我感興趣的行。我想刪除所有成功的插入,只留下Name:和INSERT INTO部分失敗的行。
“Name:”和“INSERT INTO ...”部分不一定在一行上。
這是我認為我需要匹配的偽模式:
(/Name:/)(any character)(/INSERT INTO/)(anything but not /Name:/)(/FAILED to INSERT/)
哪個會讓我失望
Name: ...
INSERT INTO ...
<span ...> FAILED to INSERT
對於每個失敗的插入
我熟悉一些正則表達式的基礎知識,但可以使用一些這方面的幫助。 我怎么能在perl或php中做到這一點?
我不認為這是正則表達式的適當任務。 通讀文件並逐行累積所需信息更為清晰。
這是一個Perl解決方案,它使用您提供的示例數據。
use strict;
use warnings;
my $info;
while (<DATA>) {
$info = '' if /Name :/;
$info .= $_;
print $info if /FAILED to INSERT/;
}
__DATA__
Name : ...
INSERT INTO (...) Values (...)
Name : ... <--- These are the lines I need
INSERT INTO (...) Values (...) <---
<span style='color:red;'>FAILED to INSERT ...</span>
Name : ...
INSERT INTO (...) Values (...)
...
產量
Name : ... <--- These are the lines I need
INSERT INTO (...) Values (...) <---
<span style='color:red;'>FAILED to INSERT ...</span>
我希望很清楚如何從文件中讀取數據。 如果在命令行上傳遞文件名,則可以將循環更改為while (<>) { ... }
。
編輯
對於單行命令解決方案,這個怎么樣
perl -0777 -ne"/FAILED to INSERT/ and print for split /(?=Name :)/" myfile
產量
Name : ... <--- These are the lines I need
INSERT INTO (...) Values (...) <---
<span style='color:red;'>FAILED to INSERT ...</span>
我相信@FritsvanCampen走在正確的軌道上。 而不是使用正則表達式,逐行遍歷整個文件就好了。 這是使用多維數組的略微修改版本。 (僅供參考,我真的不知道php,所以可能需要調整一兩次)。
$handle = fopen("strangefile.txt", "r");
$names = array();
$name = array();
while($line = fgets($handle)) {
if (substr($line, 0, 5) === "Name:") {
// start a new name array
$name = array($line);
}
else
{
// append to existing name array
$name[] = $line;
// check to see if the current name array is type 'error'
if (substr($line, 0, 31) === "<span style='color:red;'>FAILED to INSERT") {
$names[] = $name;
}
}
}
var_dump($names);
Regexps是一種痛苦,這樣的事情怎么樣?
$handle = fopen("strangefile.txt", "r");
$collect = true;
$names = array();
while($line = fgets($handle)) {
if (substr($line, 0, 31) === "<span style='color:red;'>FAILED to INSERT") {
$collect = false;
} else if ($collect && substr($line, 0, 5) === "Name:") {
$names[] = $line;
}
}
var_dump($names);
像Frits van Campen一樣,正則表達式只能是解決方案的一部分,而不是整個解決方案,如果你想快速解決這個問題。 我在答案中使用了一些其他邏輯,因為它不完全正確:
$file = new SPLFileObject("strangefile.txt");
foreach($file as $line)
{
if (isset($buffer) && substr($line, 0, 25) === "<span style='color:red;'>") {
echo $buffer . $line;
unset($buffer);
continue;
}
if (substr($line, 0, 5) === "Name:") {
$buffer = '';
}
isset($buffer) && $buffer .= $line;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.