1

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?

1 Answer 1

1

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$)'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.