Powershell - Regular Expression Multiple Matches

后端 未结 4 2082
庸人自扰
庸人自扰 2020-12-17 21:57

Maybe my reasoning is faulty, but I can\'t get this working.

Here\'s my regex: (Device\\s#\\d(\\n.*)*?(?=\\n\\s*Device\\s#|\\Z))

Try it: http://

4条回答
  •  萌比男神i
    2020-12-17 22:33

    With your existing regex, to get a list of all matches in a string, use one of these options:

    Option 1

    $regex = [regex] '(Device\s#\d(\n.*)*?(?=\n\s*Device\s#|\Z))'
    $allmatches = $regex.Matches($yourString);
    if ($allmatches.Count > 0) {
        # Get the individual matches with $allmatches.Item[]
    } else {
        # Nah, no match
    } 
    

    Option 2

    $resultlist = new-object System.Collections.Specialized.StringCollection
    $regex = [regex] '(Device\s#\d(\n.*)*?(?=\n\s*Device\s#|\Z))'
    $match = $regex.Match($yourString)
    while ($match.Success) {
        $resultlist.Add($match.Value) | out-null
        $match = $match.NextMatch()
    } 
    

提交回复
热议问题