4

I have a string that consists of

"some text \\computername.example.com\admin$".

How would I do a replace so my final result would be just "computername"

My problems appears to not knowing how to escape two backslashes. To keep things simple I would prefer not to use regexp :)

EDIT: Actually looks like stackoverflow is having problems with the double backslash as well, it should be a double backslash, not the single shown

1
  • It is not clear if you want trhe final output to show: some text computername or some text \\computername\admin$ Commented Feb 14, 2009 at 14:19

2 Answers 2

5

I don't think you're going to get away from regular expressions in this case.

I would use this pattern:

'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'

which gives you

PS C:\> 'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'

Some text computername

or if you wanted only the computername from the line:

'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1'

which returns

PS C:\> 'Some text \\computername\admin$' -replace '.*\\\\(\w+)\\(\w+)\$', '$1'

computername
Sign up to request clarification or add additional context in comments.

1 Comment

And if there could be additional text after that drive path, you can add '.*$' (ignore my quotes) to the end of that regular expression.
4

first, there is absolutely nothing wrong with the Regex method that is presented. However, if you are deadset against it, Check this:

$test = "some text \\computername.example.com\admin$"
$test.Split('\')[2].Split('.')[0]

Very simplistic testing shows that the split is marginally faster on my machine for what it is worth:

12:35:24 |(19)|C:\ PS>Measure-Command {1..10000 | %{'some text \\computername.example.com\admin$'.Split('\')[2].Split('.')[0]}}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 1
Milliseconds      : 215
Ticks             : 12159984
TotalDays         : 1.40740555555556E-05
TotalHours        : 0.000337777333333333
TotalMinutes      : 0.02026664
TotalSeconds      : 1.2159984
TotalMilliseconds : 1215.9984



12:35:34 |(20)|C:\ PS>Measure-Command {1..10000 | %{'Some text \\computername\admin$' -replace '\\\\(\w+)\\(\w+)\$', '$1'}}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 2
Milliseconds      : 335
Ticks             : 23351277
TotalDays         : 2.70269409722222E-05
TotalHours        : 0.000648646583333333
TotalMinutes      : 0.038918795
TotalSeconds      : 2.3351277
TotalMilliseconds : 2335.1277

1 Comment

Thanks EBGreen. Both worked fine, but chose your answer because it introduced me to a new element of split I had not thought of, then again I should really take the time to learn more about regex.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.