他们似乎是 used interchangeably in the documentation .有什么区别吗,即使是在意图上?
最佳答案
作为您链接到状态的文档,
m/abc/; # a regex that is immediately matched against $_ rx/abc/; # a Regex object /abc/; # a Regex object
[...] Example of difference between
m/ /
and/ /
operators:my $match; $_ = "abc"; $match = m/.+/; say $match; say $match.^name; # OUTPUT: «「abc」Match» $match = /.+/; say $match; say $match.^name; # OUTPUT: «/.+/Regex»
所以
/.../
返回 Regex
可以作为值传递的对象,并用于稍后和多次匹配,以及 m/.../
返回 Match
立即执行匹配的对象。当您打印 Match
时对象,你得到匹配的结果,当你打印 Regex
对象,您将获得正则表达式的文本表示。使用 m/.../
在 Perl 6 中,您可以访问隐式 Match
对象,$/
:Match results are stored in the
$/
variable and are also returned from the match. The result is of typeMatch
if the match was successful; otherwise it isNil
.
区别可与 Python 的
re.compile
相媲美对比 re.match
/ re.search
,并且在 Perl 5 中存在类似的区别,您可以使用 qr/.../
存储和重用正则表达式。对比 m/.../
和 /.../
用于直接匹配。正如@raiph 指出的那样,并非所有 m/.../
都会出现和 /.../
导致直接匹配。相反,Perl 5 precompiles literal (static) regexes即使没有明确要求它。 (据推测,Perl 6 也执行此优化。)
关于regex - m 和 rx 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50112461/