1

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??

1
  • i guess a typo error :), have corrected it now Commented Oct 30, 2012 at 11:37

4 Answers 4

3

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

PS> "scvmm.new.resources".Split('.')[1]
new
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant shay, i never even thought about this :), Thanks a lot
2

Or this

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

1 Comment

Like the replace, I do it the same way.
1

Like this:

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

Comments

0

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).

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.