通过正则表达式替换匹配中的单个字符 [英] Replace a single character within a match via Regex

查看:87
本文介绍了通过正则表达式替换匹配中的单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模式,我正在尝试对其进行查找和替换.当它们被数字包围时,它需要用句点替换所有破折号.

I have a simple pattern that I am trying to do a find and replace on. It needs to replace all dashes with periods when they are surrounded by numbers.

替换这些中的句点:

3-54
32-11
111-4523mhz

像这样:

3.54
32.11
111.4523mhz

但是,我不想替换以下内容中的破折号:

However, I do not want to replace the dash inside anything like these:

Example-One
A-Test

我尝试使用以下方法:

preg_replace('/[0-9](-)[0-9]/', '.', $string);

然而,这将替换整个匹配而不是中间.你如何只替换匹配的一部分?

However, this will replace the entire match instead of just the middle. How do you only replace a portion of the match?

推荐答案

preg_replace('/([0-9])-([0-9])/', '$1.$2', $string);

应该可以解决问题:)

更多解释:

通过在正则表达式中使用 (),您可以创建一个组.该组可用于替换.$1 被第一个匹配的组替换,$2 被第二个匹配的组替换,依此类推.

By using ( and ) in a regular expression, you create a group. That group can be used in the replacement. $1 get replaced with the first matched group, $2 gets replaced with the second matched group and so on.

这意味着,如果您(仅作为示例)将 '$1.$2' 更改为 '$2.$1',该操作将交换两个数字.在您的情况下,这不是有用的行为,但也许它可以帮助您更好地理解原理.

That means that if you would (just for example) change '$1.$2' to '$2.$1', the operation would swap the two numbers. That isn't useful behavior in your case, but perhaps it helps you understand the principle better.

这篇关于通过正则表达式替换匹配中的单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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