Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Match any string powershell

No matter how well I feel like I know regular expressions, they always seem to beat me.

I am looking for a universal pattern that will match any string. The only way I could figure out how to handle all these different naming conventions, was make a bunch of different regex patterns, and now I'm not even sure if all the data is getting picked up so I would have to manually cross-check it.

I am just trying to pick up anything that could possibly be within two brackets [ ] :

elseif($line -match "\[\w*\d*\]") {         
    $pars = $matches[0]
}
elseif($line -match "\[\d*\w*\]") {
    $pars = $matches[0]
}
elseif($line -match "\[\w*\d*_\w*\]") {
    $pars = $matches[0]
}
elseif($line -match "\[\w*\d*_*\w*-*\w*:*\w*\]") {
    $pars = $matches[0]
}            
elseif($line -match "\[\w*_*\w*_*\w*_*\w*_*\w*_*\w*-*\w*\]") {
    $pars = $matches[0]
}

The way I am doing it does not generate errors, but I am not sure it handles all the situations I could potentially come across. Checking manually is almost impossible with this much data.

Also, if anyone knows of a great utility for generating regex patterns it would be much appreciated. I have only been able to find regex testers which isn't very useful to me, and there is little help online for regular expressions with powershell.

like image 506
Cole9350 Avatar asked Aug 01 '13 17:08

Cole9350


People also ask

What does regex do in PowerShell?

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. Matches the beginning of the line. Matches the end of the line.

What is $Matches PowerShell?

$Matches is a variable that contains a hashtable. The hashtable (a key-pair) has a key and a value. The key is the index and the value is “what was returned as the match.” Since there is only one value in the $Matches variable, you can get to the value of the match by referencing the key-pair by its name.

What is pattern in PowerShell?

The Pattern parameter specifies the text to match Get-. Select-String displays the output in the PowerShell console. The file name and line number precede each line of content that contains a match for the Pattern parameter.


2 Answers

$a = [regex]"\[(.*)\]"
$b = $a.Match("sdfqsfsf[fghfdghdfhg]dgsdfg") 
$b.Captures[0].value
like image 79
JPBlanc Avatar answered Oct 24 '22 08:10

JPBlanc


Match everything that isn't a bracket. Create a character class that contains anything but the bracket characters:

$line -match "\[[^\[\]]+\]"
like image 7
Aaron Jensen Avatar answered Oct 24 '22 09:10

Aaron Jensen