codewario
codewario

Reputation: 21488

Formatting string in Powershell but only first or specific occurrence of replacement token

I have a regular expression that I use several times in a script, where a single word gets changed but the rest of the expression remains the same. Normally I handle this by just creating a regular expression string with a format like the following example:

# Simple regex looking for exact string match
$regexTemplate = '^{0}$'

# Later on...
$someString = 'hello'
$someString -match ( $regexTemplate -f 'hello' ) # ==> True

However, I've written a more complex expression where I need to insert a variable into the expression template and... well regex syntax and string formatting syntax begin to clash:

$regexTemplate = '(?<=^\w{2}-){0}(?=-\d$)'

$awsRegion = 'us-east-1'
$subRegion = 'east'

$awsRegion -match ( $regexTemplate -f $subRegion ) # ==> Error

Which results in the following error:

InvalidOperation: Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

I know what the issue is, it's seeing one of my expression quantifiers as a replacement token. Rather than opt for a string-interpolation approach or replace {0} myself, is there a way I can tell PowerShell/.NET to only replace the 0-indexed token? Or is there another way to achieve the desired output using format strings?

Upvotes: 1

Views: 228

Answers (1)

Theo
Theo

Reputation: 61228

If a string template includes { and/or } characters, you need to double these so they do not interfere with the numbered placeholders.

Try

$regexTemplate = '(?<=^\w{{2}}-){0}(?=-\d$)'

Upvotes: 1

Related Questions