Regex Match any string powershell

Cole9350 picture Cole9350 · Aug 1, 2013 · Viewed 62.7k times · Source

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.

Answer

JPBlanc picture JPBlanc · Aug 1, 2013
$a = [regex]"\[(.*)\]"
$b = $a.Match("sdfqsfsf[fghfdghdfhg]dgsdfg") 
$b.Captures[0].value