我有一個字符串,字符串的某些內容用雙引號引起來。 例如:Perl:讀取一個字符串中雙引號之間的內容
test_case_be "+test+tx+rx+path"
對於上述輸入欲整個字符串分成兩個部分:
- 外雙引號[
test_case_be
]我想在$temp1
存儲的字符串。 - 雙引號內的字符串[
+test+tx+rx+path
]我想將其存儲在$temp2
。
有人能幫我一個關於如何做到上述的示例代碼?
我有一個字符串,字符串的某些內容用雙引號引起來。 例如:Perl:讀取一個字符串中雙引號之間的內容
test_case_be "+test+tx+rx+path"
對於上述輸入欲整個字符串分成兩個部分:
test_case_be
]我想在$temp1
存儲的字符串。+test+tx+rx+path
]我想將其存儲在$temp2
。有人能幫我一個關於如何做到上述的示例代碼?
$str ~= /(.*)\"(.*)\"/; //capture group before quotes and between quotes
$temp1 = $1; // assign first group to temp1
$temp2 = $2; // 2nd group to temp2
這應該做你想做的。
這可以做到這一點:
my $input_string = qq(test_case_be "+test+tx+rx+path");
my $re = qr/^([^"]+)"([^"]+)"/;
# Evaluating in list context this way affects the first variable to the
# first group and so on
my ($before, $after) = ($input_string =~ $re);
print <<EOF;
before: $before
after: $after
EOF
輸出:
before: test_case_be
after: +test+tx+rx+path
$str =~ /"(.*?)"/;
$inside_quotes = $1;
$outside_quotes = $`.$';
方式一:
my $str='test_case_be "+test+tx+rx+path"';
my ($temp1,$temp2)=split(/"/,$str);
downvoter:請提一下downvoting的原因,以便我可以知道我的錯誤。 – Guru
downvote的可能原因是它沒有使用正則表達式。我不確定這是否保證;這是Perl,所以TMTOWTDI(有多種方法可以做到這一點)。 –
這裏的另一種選擇:
use strict;
use warnings;
my $string = 'test_case_be "+test+tx+rx+path"';
my ($temp1, $temp2) = $string =~ /([^\s"]+)/g;
print "\$temp1: $temp1\n\$temp2: $temp2";
輸出:
$temp1: test_case_be
$temp2: +test+tx+rx+path
一般來說,它是不使用'一個好主意'$'''或'$'';他們會對計劃中的所有正則表達式應用稅費(成本)。孤立地說,它們並不太可怕,所以對於這樣的簡單情況,可以使用它。但是,如果代碼將成爲模塊,則應該避免使用它們。如果你指出了這個問題,你的回答會很好;如果沒有這些信息,就不會爲其他人提供很好的服務。 –
謝謝,好點。我很匆忙的回答。 – arayq2