1

I am using regular expression to find strings in Powershell, and match function returns empty string lines as well as matched lines.

For the following four lines of text file input.txt,

[abc]

abc

[123]

123

The code below prints out abc/blank line/123/blank line. I expected it only prints out abc and 123, wonder how this happened.

$readArray = Get-Content(input.txt)
foreach($line in $readArray) {
   $re = [regex] *** // Find the string in bracket

   $key = $re.match($line)
   if($key -ne $null) {
      write-host -$key.group[1].value
   }
}
1
  • 1
    $re = [regex] *** looks like some kind of mistake. Can you post the actual regex you're using? Commented Aug 11, 2014 at 1:59

2 Answers 2

1

You can use this regex to get the content within tags:

\[(.*?)\]

Working demo

enter image description here

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

Comments

1

Try this (use select-string) -

Get-Content -FilePath input.txt | 
  Select-String '\[(.+?)\]') | ForEach-Object {$_.Matches[0].Groups[1].Value}

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.