[英]Perl Regex, get strings between two strings
我是Perl的新手,並嘗試使用Regex在兩個我知道會在該字符串中的標簽之間獲取一個字符串。 我已經嘗試過stackoverflow的各種答案,但是似乎沒有一個對我有用。 這是我的例子
所需的數據在$ info變量中,我想從中獲取有用的數據
my $info = "random text i do not want\n|BIRTH PLACE=Boston, MA\n|more unwanted random text";
上面字符串中的有用數據是Boston, MA
。 我通過$info =~ s/\\n//g;
從字符串中刪除了換行符$info =~ s/\\n//g;
。 現在$info
具有此字符串"random text i do not want|BIRTH PLACE=Boston, MA|more unwanted random text"
。 我認為這樣做將有助於我輕松捕獲所需的數據。
請幫助我獲取所需的數據。 我確信數據將始終在|BIRTH PLACE=
之前,並在|
。 在此之前和之后的所有內容都是不需要的文本。 如果已經回答了這樣的問題,請也指導我。 謝謝。
除了替換周圍的所有內容,您還可以搜索/\\|BIRTH PLACE=([^\\|]+)\\n\\|/
,[^ \\ |] + anything that is not a pipe
的anything that is not a pipe
一項或多項。
$info =~ m{\|BIRTH PLACE=(.*?)\|} or die "There is no data in \$info?!";
my $birth_place = $1;
這應該夠了吧。
您知道,實際上,這些換行符可能對您有所幫助。 我本來會想要一個初始正則表達式:
/^\|BIRTH PLACE=(.*)$/m
使用多行修飾符( m
)來匹配行首的^
和末尾的$
,而不僅僅是匹配字符串的首尾。 哎呀,你甚至可以變得非常瘋狂並匹配:
/(?<=^\|BIRTH PLACE=).+$/m
若要僅捕獲所需的信息,請使用后向( (?<= ... )
)斷言這是出生地信息。
為什么一次只能詛咒兩次?
因此,在perl中:
if ($info =~ m/(?<=^\|BIRTH PLACE=).+$/m) {
print "Born in $&.\n";
} else {
print "From parts unknown";
}
您大概已經從文件中讀取了此數據,這是一個糟糕的開始。 您的程序應如下所示
use strict;
use warnings;
use autodie;
open my $fh, '<', 'myfile';
my $pob;
while (<$fh>) {
if (/BIRTH PLACE=(.+)/) {
$pob = $1;
last;
}
}
print $pob;
輸出
Boston, MA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.