35

I want to extract from this string

blocked-process-report process id="process435d948" taskpriority="0" logused="0" waitresource="RID: 7:1:1132932:0" waittime= "3962166" ownerId="4641198" transactionname="SELECT" lasttranstarted="2011-09-13T17:21:54.950" XDES="0x80c5f060" lockMode="S" schedulerid="4" kpid="18444" status="susp ended" spid="58" sbid="0" ecid="0"

The value that is in bold, but only the value or 58. And this value can be with different values, sometimes 80 or 1000, etc. but always > 50.

How can I do this using regex and posh?

2 Answers 2

72

The quick and dirty:

$found = $string -match '.*spid="(\d+)".*'
if ($found) {
    $spid = $matches[1]
}

where $string is your above mentioned string. This would match any string that has spid="somenumberhere", and make the number into a matched group, which you can extract using $matches[1].

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

4 Comments

The .* will match anything before and after it on that line, its really only necessary if you used '^.*spid="(\d+)".*$'
You could leave them out, not sure on the performance impact of either way. It's probably a little cleaner/faster to leave them out, didn't really think much about it.
.* should typically not be used in regular expressions, the results can be unpredictable and performance slow because it will match the entire string before backtracking to find the next pattern in the regular expression. In this particular case only spid="(\d+)" is required for the match.
@JonAngliss: What would then be the not "quick and dirty" way?
3

Save your data in $string, then do

# Set $matches to null to avoid false positives from previous regex matches
$matches = $null
$string -match 'spid="(\d+)"'

If there is a match, the value you want will be in $matches[1]

4 Comments

Be careful, even if there is NOT a match you could still end up with data in $matches[1] from a PREVIOUS regex match.
And how does one avoid that pitfall? ^^
@Cheeso just set $matches = $null beforehand
@Cheeso Use the other answer and just check it in an if statement. -match is intended as a comparison operator after all. You can even inline the variable.

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.