如何用 REGEX 替换数字 - 比如 $1<number> [英] How to REGEX replace with numbers - like $1&lt;number&gt;

查看:35
本文介绍了如何用 REGEX 替换数字 - 比如 $1<number>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串something"并且想要得到some123".

Let's assume I have a string "something" and want to get "some123".

这将是我的正则表达式:/(some)(thing)/

This would be my regex: /(some)(thing)/

// Pseudocode
$something = 'something'
$someone = $something.replace(/(some)(thing)/, '$1one') ###works
$some123 = $something.replace(/(some)(thing)/, '$1123') ###fails

$someone 可以正常工作,但 $some123 会失败,因为解释器将查找不存在的组 1123.

$someone will work without any problems, but $some123 will fail, as the interpreter will look for group 1123, which does not exist.

有什么想法吗?谢谢!

(我正在使用 Powershell,但我认为在其他语言中也存在同样的问题,例如 PHP)

推荐答案

在 Powershell 中使用的 .NET 正则表达式中,您需要在反向引用内的捕获组 ID 周围使用 {} 以删除任何歧义:

In a .NET regex used in Powershell, you need to use {} around the capture group ID inside a backreference to remove any ambiguities:

$something = 'something'
$someone = $something -replace "(some)(thing)", '${1}one' ### someone
$some123 = $something -replace "(some)(thing)", '${1}123' ### some123

如果您不确定,也可以依赖命名捕获:

If you are unsure, you can also rely on named captures:

$someone = $something -replace "(?<some>some)(?<thing>thing)", '${some}one'

这篇关于如何用 REGEX 替换数字 - 比如 $1<number>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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