我最近编写了一个小的Perl脚本来修剪行末尾的空格并遇到意外行为.我决定在分解行时Perl必须包含行尾字符,因此测试了该理论并获得了更多意外行为. I do not应该匹配\s+$或t$......不是两者兼而有之.非常困惑.任何人都可以开导我吗?
£ cat example
I have space after me
I do not
£ perl -ne 'print if /\s+$/' example
I have a space after me
I do not
£ perl -ne 'print if /t$/' example
I do not
£
Run Code Online (Sandbox Code Playgroud)
PCRE测试仪给出了预期的结果.我也尝试了/m后缀而没有改变行为.
编辑.完整性:
£ perl -ne 'print if /e$/' example
£
Run Code Online (Sandbox Code Playgroud)
预期的行为与perl -ne 'print if...'以下相同grep -P:
£ grep -P '\s+$' example
I have a space after me
£
Run Code Online (Sandbox Code Playgroud)
可以在Ubuntu 16.04 perl v5.22.1(60和68补丁版本)和MINGW perl v5.26.1下进行复制.
您会看到当前行为,因为在example文件中第二行在\n结尾处有字符.\n是匹配的空间\s
无修饰符:默认行为....'$'仅在结尾处或在结尾处换行前匹配.
你的正则表达式\s matches a whitespace character, the set [\ \t\v\r\n\f].换句话说,它匹配空格和\n字符.然后$匹配行尾(没有字符,只有位置本身).喜欢word anchor \b匹配单词边界,并^匹配行的开头而不是第一个字符
你可以像这样重写你的正则表达式:
/[\t ]+$/
Run Code Online (Sandbox Code Playgroud)
example如果第二行没有以\n字符结尾,则内容将如下所示:
£ cat example
I have space after me
I do not£
Run Code Online (Sandbox Code Playgroud)
注意shell提示符£不在下一行
结果是不同的,因为grep抽象出像Perl的-l标志一样的行结尾.(grep -P '\n'将在文本文件中不返回任何结果grep -Pz '\n'.)
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |