我想用正則表達式來識別字符串中的引號和它們之間的詞。我也想包括雙引號和單引號。正則表達式來提取引用文本
例子,如果我有一個字符串:
The "cat and the hat" sat on a rat. The 'mouse ran' up the clock.
然後將確定以下內容:
cat and the hat
mouse ran
什麼將正則表達式是什麼?
我想用正則表達式來識別字符串中的引號和它們之間的詞。我也想包括雙引號和單引號。正則表達式來提取引用文本
例子,如果我有一個字符串:
The "cat and the hat" sat on a rat. The 'mouse ran' up the clock.
然後將確定以下內容:
cat and the hat
mouse ran
什麼將正則表達式是什麼?
#!/usr/bin/env perl
use 5.010;
my $quoted_rx = qr{
(?<quote> ['"]) # SO highlight bug "'
(?<guts>
(?: (?! \k<quote>) .) *
)
\k<quote>
}sx;
my $string = <<'END_OF_STRING';
The "cat and the hat" sat on a rat. The 'mouse ran' up the clock.
END_OF_STRING
while ($string =~ /$quoted_regex/g) {
say $+{guts};
}
每次上場時間,該帖式將在$+{quote}
和它們之間的東西,會在$+{guts}
。
只適用於U + 27(APOSTROPHE)和U + 22(引用標記)。如果你想讓它爲'this'和'this'這樣的東西工作,你必須更有趣。對於任何類型的引號,都有\p{Quotation_Mark}
屬性,對於最後的標點符號,有\p{Pi}
,對於最後的標點符號,有\p{Pf}
。
$s = 'The "cat and the hat" sat on a rat. The \'mouse ran\' up the clock.';
preg_match_all('~([\'"])(.*?)\1~s', $s, $result);
print_r($result[2]);
輸出(ideone可見):
Array ( [0] => cat and the hat [1] => mouse ran )
preg_match_all
保存在數組的數組中的所有匹配的結果。您可以更改結果的排列方式,但默認情況下,第一個數組包含整體匹配($0
或$&
),第二個數組包含第一個捕獲組的內容($1
,$2
等),依此類推。
在這種情況下,$result[0]
是來自所有匹配的完整引用字符串,$result[1]
是引號,而$result[2]
是引號之間的任何內容。
謝謝。我會測試一下。 – Jason 2010-11-08 15:14:01
有沒有可以逃脫的引號:''這不好玩!',馬爾利抱怨道。''? – tchrist 2010-11-08 00:57:08
什麼正則表達式語言? – tchrist 2010-11-08 01:00:13
沒錯,沒有想到這一點。 – Jason 2010-11-08 01:01:28