views:

199

answers:

2

Hi,

How can i extricate substring from string using powershell ? I have this string: "-----start-------Hello World------end-------", i have to the hello world. What is the best way to do that?

Thanks!

+1  A: 

The SubString method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.

PS > "test_string".substring(0,4)
Test
PS > "test_string".substring(4)
_stringPS >

link text

But this is easier...

 $s = 'Hello World is in here Hello World!'
 $p='Hello World'
 $s -match $p

And finally, to recurse through a directory selecting only the txt files and searching for occurence of "Hello World"

dir -rec -filter *.txt | select-string 'Hello World'
nineowls
+1: however a regex capturing whats between the start and end tags would be better e.g. "-----start-------(.+?)------end-------" (untested regex, and I'm no regex guru)
Binary Worrier
A: 

The -match operator tests a regex, combine it with the magic variable $matches to get your result

PS C:\> $x = "----start----Hello World----end----"
PS C:\> $x -match "----start----(?<content>.*)----end----"
True
PS C:\> $matches['content']
Hello World

Whenever in doubt about regex-y things, check out this site: http://www.regular-expressions.info

Matt Woodard