Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

regex - Have trouble understanding capturing groups and back references

Wishing to put some order into my knowledge of regular expressions I decided to go through a book about them, Introducing Regular Expressions. And I know it's silly but one of the introductory examples doesn't make sense to me.

(d)d1

Sample text:

123-456-7890

(should capture the first number, 123)

Can anyone explain what is going on in here?

As far as I can figure out, the first d captures the number 123. The 1 backreferences (marks) the group for later use. The parenthesis limit the scope of the group. But what does the second d does?

Simple explanation, like to a small child or a golden retriever are prefered.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

d is just one digit.

This regular expression doesn't match the "123-456-7890" string but it would match "323" (which could be part of a greater string, for example "323-456-7890") :

 (d) : first digit ("3")
 d   : another digit ("2")
 1   : first group (which was "3")

Now, if your book pretends that (d)d1 should capture "123" in "123-456-7890", then it might contain an error...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...