'Powershell Regex match statement
Trying to get nxxxxx number as the output from below input,
uniqueMember: uid=n039833,ou=people,ou=networks,o=test,c=us
uniqueMember: uid=N019560, ou=people, ou=Networks, o=test, c=Us
Tried,
[Regex]::Matches($item, "uid=([^%]+)\,")
but this gives,
Groups : {0, 1}
Success : True
Name : 0
Captures : {0}
Index : 14
Length : 43
Value : uid=N018315,ou=people,ou=Networks,o=test,
Success : True
Name : 1
Captures : {1}
Index : 18
Length : 38
Value : N018315,ou=people,ou=Networks,o=test
Some help with improving the match statement appreciated ..
Solution 1:[1]
You can use
[Regex]::Matches($s, "(?<=uid=)[^,]+").Value
To save in an object variable:
$matches = [Regex]::Matches($s, "(?<=uid=)[^,]+").Value
Output:
n039833
N019560
Details:
(?<=uid=)
- a positive lookbehind that requiresuid=
text to appear immediately to the left of the current location[^,]+
- one or more chars other than a comma.
Solution 2:[2]
You can use a capture group and prevent matching ,
and if you don't want to match %
you can also exclude that.
$s = "uniqueMember: uid=n039833,ou=people,ou=networks,o=test,c=us\nuniqueMember: uid=N019560, ou=people, ou=Networks, o=test, c=Us"
[regex]::Matches($s,'uid=([^,]+)') | Foreach-Object {$_.Groups[1].Value}
Output
n039833
N019560
Note that in the current pattern there should be a trailing comma present. If that is not ways the case, you can omit matching that from the pattern. If you only want to exclude matching a comma, the pattern will be:
uid=([^,]+)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |