I found PowerShell's regex match but could not find Powershell's equivalent of Python's regex search.
The below is the example in Python.
>>> inputstring = "iqn.2007-11.com.storage:srmgrsmisvstvol2-ju7wjffssldf-df-sdf-ewr-v0dd04708bb13b686.000"
>>> match = re.search(r"(\w*-){4}(\w*)", inputstring, re.IGNORECASE)
>>> match.group()
'srmgrsmisvstvol2-ju7wjffssldf-df-sdf-ewr'
The PowerShell equivalent of your Python code would look somewhat like this:
$inputstring = 'iqn.2007-11.com.storage:srmgrsmisvstvol2-ju7wjffssldf-df-sdf-ewr-v0dd04708bb13b686.000'
if ($inputstring -match '(\w*-){4}(\w*)') {
$matches[0]
}
The -match
operator (which is case-insensitive by default) is used for checking a string against a regular expression. If matches are found the automatic variable $matches
is populated with those matches. The matches can then be accessed by index: 0 gives the full match, 1 the first captured group, 2 the second captured group, etc.
In addition to the (implicitly case-insensitive) base version ( -match
) PowerShell comparison operators usually have explicit case-sensitive and case-insensitive versions ( -cmatch
, -imatch
).
$inputstring -match '(\w*-){4}(\w*)' # case-insensitive
$inputstring -imatch '(\w*-){4}(\w*)' # case-insensitive
$inputstring -cmatch '(\w*-){4}(\w*)' # case-sensitive
You can also enable or disable case-sensitivity via so-called miscellaneous constructs inside the regular expression, which take precedence over the operator's case-sensitivity:
$inputstring -imatch '(?-i)(\w*-){4}(\w*)' # case-sensitive
$inputstring -cmatch '(?i)(\w*-){4}(\w*)' # case-insensitive
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.