我想用正则表达式来识别字符串中的引号和它们之间的词。我也想包括双引号和单引号。正则表达式来提取引用文本
例子,如果我有一个字符串:
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