gpt4 book ai didi

regex - 如何用正则表达式替换数字 - 如 $1

转载 作者:行者123 更新时间:2023-12-01 09:34:34 28 4
gpt4 key购买 nike

假设我有一个字符串“something”并且想要得到“some123”。

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

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

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

有任何想法吗?谢谢!

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

最佳答案

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

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

enter image description here

如果您不确定,您也可以依靠 命名捕获 :
$someone = $something -replace "(?<some>some)(?<thing>thing)", '${some}one'

enter image description here

关于regex - 如何用正则表达式替换数字 - 如 $1<number>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35435947/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com