当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - Why isn't the backslash printed when I print the backreference?

问题描述:

Why in the following snippet:

~$ perl -e '

my $var = "SRC=array.c builtin.c eval.c field.c gawkmisc.c io.c \ main.c ";

$var =~ /^\w+=(.*)/;

print "$1\n";

'

array.c builtin.c eval.c field.c gawkmisc.c io.c main.c

The \ is not printed in the backreference. . obviously matches \ in the string text since the capture is uptill the end of the line, so why isn't it printed?

Why would I need to escape it in this context?

网友答案:

The backslash character is special in that it indicates that what follows is not literal. For example, with text like "line 1\nline 2\n" you see two instances of "\n"... the backslash says what follows is a special meaning, and n indicates a carriage return. In your case, "\ " has no special meaning so only the space is printed.

If you truly want to see the backslash, "\\" will do it.

网友答案:

The "\ " is considered an "escaped space". If you really want to see the \, you need \\ in your string.

If you look closely at your output you will see

io.c  main.c
    ^^

There are two spaces...

So tiny change needed:

perl -e '
my $var = "SRC=array.c builtin.c eval.c field.c gawkmisc.c io.c \\ main.c ";  
$var =~ /^\w+=(.*)/;  
print "$1\n";  
'
array.c builtin.c eval.c field.c gawkmisc.c io.c \ main.c  
分享给朋友:
您可能感兴趣的文章:
随机阅读: