“\ 2”在正则表达式的末尾是什么意思

时间:2022-12-31 15:48:07

I have the following assignment:

我有以下任务:

Words of a song are in a file called stairway.txt. Which of the following lines will be printed out after this command:

歌曲的单词位于名为stairway.txt的文件中。在此命令之后将打印以下哪一行:

grep -E '(^.{4})(.{2}).*[ ]\2' stairway.txt

(a) Yes, there are two paths you can go by but in the long run

(b) Its just a spring clean for the May queen.

(c) Don't be alarmed now.

(d) If there's a bustle in your hedgerow.

(e) Theres still time to change the road you're on.

I don't understand what does the \2 at the end mean?

我不明白\ 2到底意味着什么?

1 个解决方案

#1


12  

It is a backreference.

这是一个反向引用。

From http://www.selectorweb.com/grep_tutorial.html:

来自http://www.selectorweb.com/grep_tutorial.html:

Backreference is an expression \n where n is a number. It matches the contents of the n'th set of parentheses in the expression.

反向引用是一个表达式\ n,其中n是数字。它匹配表达式中第n组括号的内容。

Also, the answer is (d):

另外,答案是(d):

$ grep -E '(^.{4})(.{2}).*[ ]\2' test.txt
If there's a bustle in your hedgerow.

#1


12  

It is a backreference.

这是一个反向引用。

From http://www.selectorweb.com/grep_tutorial.html:

来自http://www.selectorweb.com/grep_tutorial.html:

Backreference is an expression \n where n is a number. It matches the contents of the n'th set of parentheses in the expression.

反向引用是一个表达式\ n,其中n是数字。它匹配表达式中第n组括号的内容。

Also, the answer is (d):

另外,答案是(d):

$ grep -E '(^.{4})(.{2}).*[ ]\2' test.txt
If there's a bustle in your hedgerow.