SAS
SAS

Reputation: 4035

replace whole string if contains substring

I want to completely replace a string if it contains a specific substring, using replace. How can this be done?

I have tried the following, with expected output "STRING":

$a="abc123STRINGabc123"
$a.replace('*STRING*','STRING')

Upvotes: 1

Views: 641

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Use the -replace operator and a regular expression.

$a = 'abc123STRINGabc123'
$b = 'abc123foobarabc123'

$srch = 'STRING'
$repl = 'GNIRTS'

$pattern = '.*{0}.*' -f [regex]::Escape($srch)

$a -replace $pattern, $repl   # output: GNIRTS
$b -replace $pattern, $repl   # output: abc123foobarabc123

Upvotes: 2

Related Questions