我正在嘗試將文本拆分為“步驟”假設我的文本是
my $steps = "1.Do this. 2.Then do that. 3.And then maybe that. 4.Complete!"
我希望輸出是:
"1.Do this."
"2.Then do that."
"3.And then maybe that."
"4.Complete!"
我對正則運算式并不是那么好,所以幫助會很棒!
我嘗試了很多組合,例如:
split /(\s\d.)/
但它將編號與文本分開
uj5u.com熱心網友回復:
我確實會使用split. 但是您需要使用前瞻從匹配中排除該數字。
my @steps = split /\s (?=\d \.)/, $steps;
uj5u.com熱心網友回復:
所有步驟描述都以數字開頭,后跟句點,然后是非數字,直到下一個數字。所以捕捉所有這些模式
my @s = $steps =~ / [0-9] \. [^0-9] /xg;
say for @s;
這僅在步驟描述中肯定沒有數字時才有效,就像任何依賴匹配數字的方法一樣(即使后面跟著一個句點,對于十進制數字)?
如果那里可能有數字,我們需要更多地了解文本的結構。
另一個要考慮的分隔模式是結束句子的標點符號(.在!這些示例中),如果步驟描述中沒有這樣的字符并且沒??有多個句子
my @s = $steps =~ / [0-9] \. .*? [.!] /xg;
根據需要增加結束專案描述的模式串列,比如使用?, 和/或."序列,因為標點符號通常放在引號內。?
如果一個專案可以有多個句子,或者在句子中間使用標點符號(也許作為參考的一部分),那么通過結合腳注來加強專案結束的條件——句末標點符號,然后是數字 句號
my @s = $steps =~ /[0-9] \. .*? (?: \."|\!"|[.\!]) (?=\s [0-9] \. | \z)/xg;
如果這還不夠好,那么我們真的需要對該文本進行更精確的描述。
?一種使用“數字周期”模式來分隔專案描述的方法,例如
/ [0-9] \. .*? (?=\s [0-9] \. | \z) /xg;
(或在前瞻中split)失敗,文本如下
1. Only $2.50 或 1. Version 2.4.1 ...
?要包括我們想要1. Do "this."的文本2. Or "that!"
/ [0-9] \. .*? (?: \." | !" | [.!?]) /xg;
uj5u.com熱心網友回復:
以下示例代碼演示了正則運算式%steps在一行代碼中填充哈希的能力。
一旦獲得資料,您就可以按照自己的意愿對其進行切片和切片。
檢查樣品是否符合您的問題。
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
my($str,%steps,$re);
$str = '1.Do this. 2.Then do that. 3.And then maybe that. 4.Complete!';
$re = qr/(\d )\.(\D )\./;
%steps = $str =~ /$re/g;
say Dumper(\%steps);
say "$_. $steps{$_}" for sort keys %steps;
輸出
$VAR1 = {
'1' => 'Do this',
'2' => 'Then do that',
'3' => 'And then maybe that'
};
1. Do this
2. Then do that
3. And then maybe that
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/528211.html
標籤:正则表达式perl
上一篇:Perl模塊未安裝。sh:1:gzip:執行格式錯誤
下一篇:無法讓多行正則運算式匹配字串
