user3103598
user3103598

Reputation: 185

Powershell replace with wild card

I want to replace a domain string

"random.org" to take everything after and the full stop

$newstring = $domain.replace #Not sure what else to add

I know to use .Replace, but not sure how to use the wildcard feature and how it works.

Can I have a little help please!

Thanks!!!

Upvotes: 0

Views: 13876

Answers (3)

Adil Hindistan
Adil Hindistan

Reputation: 6605

PowerShell's "-replace" operator, which is used with regex is often confused with ".replace" method on strings. There are many way you can skin that cat, but your question is a bit vague to answer precisely.

Regardless, in your case you do not want to use the "method"

string.replace()

instead use, as others suggested, the "operator"

string -replace "regex_to_be_replaced_here", "replacement_here"

A couple of examples have been provided already. I would go with Joey's, where his regex says "start from the beginning of the string and match everything except a dot (".") and replace them with nothing, effectively erasing them leaving the parts after dot behind:

$newstring = $domain -replace '^[^.]*', ''

You might also be able to use .split method or -split operator

string.split("some_delim") or string -split "some_delim"

Example:

$domain = "random.org"    
$domain.split('.')[-1]
org

split operator, like -replace operator uses regex, where '.' has a special meaning, so you need to escape it, telling regex that you really want to match a '.'

 ($domain -split '\.')[-1]
 org

If you already know how many characters from the right side of the string you need, you may even use substring(). Following means give me the last 3 chars of $domain:

$domain.substring($domain.length - 3)
org

Upvotes: 2

lit
lit

Reputation: 16236

If you are seeking only the TLD (.com, .org, .gov, etc.), then you can use -replace with a capture.

PS C:\src\t> "www.myhome.org"  -replace '^[^.]*'
.myhome.org
PS C:\src\t> "www.myhome.org"  -replace '^.*(\..*)', '$1'
.org

Upvotes: 0

Joey
Joey

Reputation: 354406

You can use PowerShell's -replace operator, which uses regular expressions:

$newstring = $domain -replace '^[^.]*'

If you're wondering about the lack of the replacement string, that is optional in PowerShell; above code is functionally identical to

$newstring = $domain -replace '^[^.]*', ''

Upvotes: 2

Related Questions