正则表达式 $1、$2 等 [英] Regex $1, $2, etc

查看:44
本文介绍了正则表达式 $1、$2 等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试用 PHP 做一些正则表达式操作,我在这方面不是很熟练.似乎当我在字符串上使用像 preg_replace 这样的正则表达式函数时,我可以通过某种名为 $1、$2 等的变量访问被正则表达式替换的字符串.这叫什么,我如何使用它?

I've been trying to do some regex operations in PHP, and I'm not very skilled in this area. It seems that when I use a regex function like preg_replace on a string, I can access the regex-replaced strings by some sort of variables named $1, $2, and so on. What is this called and how can I use it?

推荐答案

这些在正则表达式术语中称为 backreferences(更多关于 此处).您可以使用它们来引用正则表达式或替换字符串中的捕获组(或子模式,由 () 包围).

These are known in regex terminology as backreferences (more on that here). You use them to refer to capture groups (or subpatterns, surrounded by ()) within your regex or in the replacement string.

示例:

/* 
 * Replaces abcd123 with 123abcd, or asdf789 with 789asdf.
 * 
 * The $1 here refers to the capture group ([a-z]+),
 * and the $2 refers to the capture group ([0-9]+).
 */
preg_replace('/([a-z]+)([0-9]+)/', '$2$1', $str);

这篇关于正则表达式 $1、$2 等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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