Regex Match any string powershell

2020-08-09 10:39发布

问题:

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.

回答1:

$a = [regex]"\[(.*)\]"
$b = $a.Match("sdfqsfsf[fghfdghdfhg]dgsdfg") 
$b.Captures[0].value


回答2:

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

$line -match "\[[^\[\]]+\]"


回答3:

Focusing to

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

I think \[.*\] is what you are looking for.

Explanation
Sice [ and ] have special purposes, so you need to use \ before those characters.
.(dot) stands for any character and
* stands for any number of repetition of the previous charector.
Here, the previous character is ., so .* stands for any general string.