无法理解捕获组和反向引用 [英] Have trouble understanding capturing groups and back references

查看:26
本文介绍了无法理解捕获组和反向引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望整理一下我对正则表达式的了解,我决定阅读一本关于它们的书,正则表达式介绍.我知道这很愚蠢,但其中一个介绍性示例对我来说没有意义.

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)\d\1

示例文本:

123-456-7890

(应该捕获第一个数字,123)

(should capture the first number, 123)

谁能解释一下这里发生了什么?

Can anyone explain what is going on in here?

据我所知,第一个 \d 捕获数字 123.\1 反向引用(标记)该组以供以后使用.括号限制了组的范围.但是第二个 \d 做了什么?

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.

推荐答案

\d 只是 一个 数字.

此正则表达式与 "123-456-7890" 字符串不匹配,但它会匹配 "323"(它可能是更大字符串的一部分,例如 "323-456-7890") :

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")

现在,如果你的书假设 (\d)\d\1 应该在 "123-456-7890" 中捕获 "123"代码>,那么它可能包含一个错误...

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

这篇关于无法理解捕获组和反向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆