PowerShell
PowerShell

Reputation: 2081

Regular expression using powershell

Here's is the scenario, i have these lines mentioned below i wanted to extract only the middle character in between two dots.

 "scvmm.new.resources" --> This after an regular expression match should return only "new"
 "sc.new1.rerces" --> This after an regular expression match should return only "new1"

What my basic requirement was to exract anything between two dots anything can come in prefix and suffix

 (.*).<required code>.(.*)

Could anyone please help me out??

Upvotes: 1

Views: 741

Answers (4)

vonPryz
vonPryz

Reputation: 24091

You don't actually need regular expressions for such a trivial substring extraction. Like Shay's Split('.') one can use IndexOf() for similar effect like so,

$s = "scvmm.new.resources"
$l = $s.IndexOf(".")+1
$r = $s.IndexOf(".", $l)
$s.Substring($l, $r-$l) # Prints new

$s = "sc.new1.rerces"
$l = $s.IndexOf(".")+1
$r = $s.IndexOf(".", $l)
$s.Substring($l, $r-$l) # Prints new1

This looks the first occurence of a dot. Then it looks for first occurense of a dot after the first hit. Then it extracts the characters between the two locations. This is useful in, say, scenarios in which the separation characters are not the same (though the Split() way would work in many cases too).

Upvotes: 0

CB.
CB.

Reputation: 60976

Like this:

 ([regex]::Match("scvmm.new1.resources", '(?<=\.)([^\.]*)(?=\.)' )).value

Upvotes: 1

Himanshu
Himanshu

Reputation: 2454

Or this

'scvmm.new.resources' -replace '.*\.(.*)\..*', '$1'

Upvotes: 2

Shay Levy
Shay Levy

Reputation: 126912

You can do that without using regex. Split the string on '.' and grab the middle element:

PS> "scvmm.new.resources".Split('.')[1]
new

Upvotes: 3

Related Questions