![](/img/trans.png)
[英]Regex matches for single line of text, but not when multiple lines of text are matched against?
[英]Reading line by line when text spans multiple lines
我在將記錄#SWCR000173解析為@fieldValues時遇到問題,因為它跨越多行。 我的生產數據集中經常會出現此問題。 我了解我一次只能讀一行。 我試圖找出我的選擇,並做了很多stackoverflow和google研究。 我想我可以嘗試在行末找到回車符,然后再推送到數組並與下一行連接。 但是,可能還有一個我不知道的更干凈的答案。 可以查看我的代碼和數據集嗎? 提前非常感謝您。
數據集示例:
<record>SWCR000171</record><Title>Example Single Line Title 1</Title>
<record>SWCR000172</record><Title>Example Single Line Title 2</Title>
<record>SWCR000173</record><Title>Example Multiple
Line Title 1</Title>
<record>SWCR000174</record><Title>Example Single Line Title 3</Title>
Perl代碼:
open ($inFile, '<', $inputFile) or die $!;
while ($inFileLine = <$inFile>) {
#Create an array of fieldnames from the line being processed
@fieldNames = $inFileLine =~ m(<\/(.*?)>)g;
#Create an array of data values from the line being processed
@fieldValues = $inFileLine =~ m(>([^<]+)<)g;
#Populate a variable with the record number for the line being processed
$dbid = @fieldValues[1];
#Submit data to database for all fields after the dbid (elements>1)
$entity = $session->GetEntityByDbId("SWCR",$dbid);
$entity->EditEntity("AdminModify");
$entity->SetFieldValue($fieldNames[$_],$fieldValues[$_]) for (2 .. $#fieldNames);
$entity->SetFieldValue("AdminModifyReason",$inputFile);
$entity->Validate();
$commit = $entity->Commit();
}
close $inFile;
聽起來聽起來像是破記錄的風險-它看起來像XML,但事實並非如此,它將以與您在注釋中看到的完全相同的方式超越未來的維護程序員。
更糟糕的是-這是帶有換行符的任意定界格式-結果變得越來越難解析。
鑒於您所擁有的-您的問題是while循環。 默認情況下, while ( <$fh> ) {
讀取一行。
您確實需要一個唯一的記錄分隔符-如果您的數據包含換行符,則不是。
根據您的數據,建議您最好將分隔符設置為</Title>
例如;
local $/ = '</Title>';
然后,您的while循環將讀取多行,直到到達該結束標記為止。 這完全基於以下假設:不是XML,而是記錄順序是一致的。 否則,您將必須執行以下操作:
#linefeed delim
my $buffer;
while ( my $line = <$fh> ) {
$buffer .= $line;
if ( $line =~ m/>$/ ) {
## do processing, because the line ends in a tag
#empty buffer
$buffer = "";
}
}
但是,認真的說-像這樣做偽造的XML仍然不是一個好主意,這是另一個原因。 (XML解析器可以處理多行記錄沒有問題)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.