powershell与Python的Regex搜索是什么等价的?

2024-06-28 22:12:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了PowerShell的regex匹配项,但找不到与Python的regex搜索等价的PowerShell。你知道吗

下面是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'

Tags: recom示例dfsearchmatchstorageregex
1条回答
网友
1楼 · 发布于 2024-06-28 22:12:55

与Python代码等效的PowerShell类似的代码如下所示:

$inputstring = 'iqn.2007-11.com.storage:srmgrsmisvstvol2-ju7wjffssldf-df-sdf-ewr-v0dd04708bb13b686.000'
if ($inputstring -match '(\w*-){4}(\w*)') {
    $matches[0]
}

-matchoperator(默认情况下不区分大小写)用于根据正则表达式检查字符串。如果找到匹配项,automatic variable$matches将填充这些匹配项。然后可以通过索引访问匹配项:0表示完全匹配,1表示第一个捕获的组,2表示第二个捕获的组,等等

除了(隐式不区分大小写)基本版本(-match)之外,PowerShell比较运算符通常具有显式区分大小写和不区分大小写的版本(-cmatch-imatch)。你知道吗

$inputstring -match '(\w*-){4}(\w*)'   # case-insensitive
$inputstring -imatch '(\w*-){4}(\w*)'  # case-insensitive
$inputstring -cmatch '(\w*-){4}(\w*)'  # case-sensitive

您还可以通过正则表达式内部的miscellaneous constructs启用或禁用区分大小写,它优先于运算符的区分大小写:

$inputstring -imatch '(?-i)(\w*-){4}(\w*)'  # case-sensitive
$inputstring -cmatch '(?i)(\w*-){4}(\w*)'   # case-insensitive

相关问题 更多 >