只是想了解正则表达式.以下是部分代码.它逐行读取文件,并具有以下表达式以在任一端跳出空格行.
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 正则表达式中的大括号
发布评论