正则表达式以匹配"{number}" [英] Regex to match "{number}"

查看:368
本文介绍了正则表达式以匹配"{number}"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用"test(Z)"替换"{Z}",其中Z始终是使用PHP和正则表达式的无符号整数(除非有更快的方法?).

I need to replace "{Z}" with "test(Z)" where Z is always an unsigned integer using PHP and regular expressions (unless there's a faster way?).

$code='{45} == {2}->val() - {5}->val()';
// apply regex to $code
echo $code;
// writes: test(45) == test(2)->val() - test(5)->val()

棘手的部分是,它需要在速度和内存使用方面以最佳方式完成.

The tricky part is that it needs to be done in the best manner possible concerning speed and memory use.

推荐答案

缺少的行是这样的:

$code = preg_replace('/{([0-9]+)}/', 'test($1)', $code);

工作原理:


{       match a literal {
(       start a capturing group
[0-9]+  one or more digits in 0-9
)       end the capturing group
}       match a literal }

替换字符串中的$ 1表示第一个(也是唯一一个)捕获组捕获的字符串.

The $1 in the replacement string refers to the string captured by the first (and only) capturing group.

这篇关于正则表达式以匹配"{number}"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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