我正在研究来自http://shop.oreilly.com/product/9780596528126.do的正则表达式,我发现$比^要复杂一些,这让我感到惊讶,因为我认为它们是“对称的”,除非它们被转义成字面上的对应词。
事实上,在第129页中,它们的描述略有不同,更多的词都倾向于使用$;然而,我仍然对此感到困惑。
^,只描述了两个明确的备选方案:
^在搜索文本的开头匹配,如果在增强的行锚模式下,则在任何换行符之后匹配。.$.火柴
$,我对它的描述更加模糊:
$...匹配在目标字符串的末尾,以及字符串结束换行符之前。后者是常见的,允许像s$这样的表达式(表面上,匹配“以s结尾的行”)匹配…s<NL>,以s结尾的行以结束换行符结尾。$的另外两个常见含义是只匹配目标文本的末尾,并在任何换行符之前进行匹配。
后两个意思似乎与^描述的意思相当对称,但是字符串结尾的换行符呢?
目前,搜索[regex] "string-ending newline"只给出了一、二和三的结果,它们都参考了
$匹配字符串的结束位置或字符串结束换行符之前的位置。在基于行的工具中,它匹配任何行的结束位置.
发布于 2020-03-07 15:37:12
零宽度断言$在字符串末尾或行结束符之前(如果有的话)断言位置。
在perl中使用这些代码片段将更加清楚。
$str = 'abc
foo';
$str =~ s/\w+$/#/;
print "1. <" . $str . ">\n\n";
$str = 'abc
foo
';
$str =~ s/\w+$/#/;
print "2. <" . $str . ">\n\n";
$str = 'abc
foo
';
$str =~ s/\w+$/#/;
print "3. <" . $str . ">\n\n";这将产生这样的输出:
1. <abc
#>
2. <abc
#
>
3. <abc
foo
>如您所见,$与1和2匹配,因为$匹配字符串末尾(案例1)或行结束前(案例2)。但是,案例3仍然不匹配,因为行中断不在字符串的末尾。
发布于 2020-03-07 22:32:26
“字符串结束换行符”指的是一个行提要,它是字符串的最后一个字符。
无/m
$匹配字符串末尾的行提要和字符串末尾的行提要。
"abc\ndef\n" =~ /^abc$/ # Doesn't match at embedded line feed
"abc\ndef\n" =~ /^abc\n$/ # Doesn't match after embedded line feed
"abc\ndef\n" =~ /^abc\ndef$/ # Matches at string-ending line feed
"abc\ndef\n" =~ /^abc\ndef\n$/ # Matches at end of string它等价于\Z,这相当于(?=\n\z|\z)。
用/m
$在行提要之前和字符串的末尾进行匹配。
"abc\ndef\n" =~ /^abc$/ # Matches at embedded line feed
"abc\ndef\n" =~ /^abc\n$/ # Doesn't match after embedded line feed
"abc\ndef\n" =~ /^abc\ndef$/ # Matches at string-ending line feed
"abc\ndef\n" =~ /^abc\ndef\n$/ # Matches at end of string它相当于(?=\n|\z)。
当您想要精确匹配时,使用\z。
/xyz\z/ # String ends with "xyz"当您想忽略尾随行提要时,将使用$。
/xyz$/ # Line ends with "xyz". The string might end with a line feed.例如,
"jkl" =~ /^jkl$/ # Matches at end of string
"jkl" =~ /^jkl\z/ # Matches at end of string
"jkl\n" =~ /^jkl$/ # Matches at string-ending line feed
"jkl\n" =~ /^jkl\z/ # Doesn't match at string-ending line feed如果与您还没有执行的行进行匹配,则$非常有用。
while (<>) {
next if /^foo$/;
...
}\z在剩下的时间是有用的。
请注意,其他regex引擎的行为可能有所不同,甚至那些类似Perl的引擎。例如,在JavaScript中,没有/m的$只匹配字符串的末尾。
发布于 2020-03-07 15:19:06
要点是,$将在(a)换行符之前和文件或输入字符串的末尾匹配,该字符串可以或不能以(a)换行符结尾。
https://stackoverflow.com/questions/60579000
复制相似问题