Perl 正则表达式中的大括号

编程入门 行业动态 更新时间:2024-10-24 06:36:56
本文介绍了Perl 正则表达式中的大括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

只是想了解正则表达式.以下是部分代码.它逐行读取文件,并具有以下表达式以在任一端跳出空格行.

just trying to get my head around regexps. The following is part of the code. It read a file line by line and it has the following expression to trip the line of white spaces at either end.

\A 匹配行首\s+一个或多个空格\z 匹配行尾

\A match the start of the line \s+ one or more white spaces \z match the end of the line

while (<$fh>) { s{\A\s+}{}; s{\s+\z}{}; }

我挣扎的部分是大括号.我能找到的关于它们的唯一文件说明它们是一个乘数.我读 s{\A\s+}{}; 如果行首和空格替换为空,但这是我的猜测.我希望确认这一点以及大括号在此正则表达式中的含义

The part I am struggling with is the curly brackets. The only documentation I can find on them states they act as a multiplier. I read s{\A\s+}{}; if start of line AND white spaces replace with nothing, but that's my guess. I am looking to confirm that and what the curly brackets means in this regexps

推荐答案

devnull 已经给出了正确的答案,但我觉得要添加的内容比评论中的要多.

devnull has already given the correct answer, but I felt there was more to add than fits in a comment.

s{}{} 只是 s/// 替换运算符,但与不同的分隔符一起使用.您几乎可以使用任何字符作为分隔符,包括不同类型的平衡括号,例如s#foo#bar#, s[foo][bar].

s{}{} is simply the s/// substitution operator, but used with a different delimiter. You can use just about any character as delimiter, including balanced parentheses of different types, e.g. s#foo#bar#, s[foo][bar].

您可以使用它来避免在匹配字符串中转义分隔符.比如匹配路径时:

You use this to avoid escaping delimiters in the matching string. Such as when matching paths:

s#/foo/bar/baz#/foo/baz/bax#

使用默认斜杠分隔符 /:

Looks better than the equivalent, using the default slash delimiter /:

s/\/foo\/bar\/baz/\/foo\/baz\/bax/

老实说这很令人困惑.

在您的情况下,没有真正的理由使用不同的分隔符,因此我认为最好使用原始分隔符编写替换:

In your case, there is no real reason to use a different delimiter, so the substitutions are in my opinion best written with the original delimiter:

s/\A\s+// s/\s+\z//

更多推荐

Perl 正则表达式中的大括号

本文发布于:2023-06-05 19:40:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/526435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   正则表达式   Perl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!