Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to REGEX replace with numbers - like $1<number>

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

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 will work without any problems, but $some123 will fail, as the interpreter will look for group 1123, which does not exist.

Any ideas? Thank you!

(edit: I am using Powershell, but I think it's the same problem in other languages, like PHP, too)

like image 895
Gerfried Avatar asked Mar 13 '23 06:03

Gerfried


1 Answers

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

enter image description here

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

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

enter image description here

like image 51
Wiktor Stribiżew Avatar answered Mar 24 '23 12:03

Wiktor Stribiżew