当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 和 Regex(查找、替换、出现……)

作者:精品下载站 日期:2024-12-14 07:35:35 浏览:13 分类:玩电脑

PowerShell 和 Regex(查找、替换、出现……)


想要充分利用 PowerShell?细化搜索?只是好起来吗?然后查看正则表达式。正则表达式语句使看似不可能的事情成为可能。在这篇博文中,我向您展示了一些您可以构建的正则表达式示例。让我们深入了解一下。

我将介绍以下场景和问题:

  1. 找到一些东西(字母、点……)
  2. 查找并删除出现的情况
  3. 查找或删除德语变音符号
  4. 根据模式查找电子邮件地址

代码示例

# Does it contain letters ? ==> '\w'

'Patrick' -match '\w'

# Does it contain digits ? ==> '/d'

'Patrick' -match '\d'

# Find a dot

'[email protected]' -match '\.'

'patrickgruenauer@outlookcom' -match '\.'

# Does it begin with P ? ==> '^P'

'Patrick' -match '^P'

'Patrick' -match '^a'

# Does it begin with a digit or letter ? Note: use -cmatch instead -match for case-sensitive matches

'Patrick' -cmatch '^[A-Z]'

'Patrick' -cmatch '^[a-z]'

'Patrick' -match '^[0-9]'

# Does it end with a letter ? Note: use -cmatch for case-sensitive matches

'Patrick' -cmatch '[A-Z]$'

'Patrick' -cmatch '[a-z]$'

# Remove German Umlauts

$names = 'Patrick Grünauer', 'Arnold Schwarzenegger', 'Hans Fetisch'

$names -match '[^a-zA-Z ]'

$names -match '[^a-zA-Z ]' -replace 'ü','ue' -replace 'ä','ae' -replace 'ö','oe'

# Remove every second occurence

<# 

^([^.]+.[^.]+)      ==> Create a group (first group is always $1). Capture the first two separated tokens at the start (^).
$1*                 ==> Search for group $1 and replace next character (.) with *
                    Note: [^.] means no dot.

#>

'[email protected]' -replace '^([^.]+.[^.]+).', '$1*'                   # replace second dot

'[email protected]' -replace '^([^.]+).', '$1*'                         # replace first dot

'[email protected]' -replace '^([^.]+.[^.]+.[^.]+).', '$1*'         # replace third (last) dot

'[email protected].' -replace '[.]$', ''                            # replace dot at the end of string

$a = '[email protected].'
$b = [regex]::Match($a, '^([^.]+.[^.]+.[^.]+).').value
$b.substring(0,$b.length-1)                                                         # remove everthing after third dot

# Does it end with 2 or 4 letters ? ==> to find e-mail addresses ?
# Source unknown. Thanks to the unknown forum member in a regex forum

'[email protected]' -match '^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]{2,4}$'    

'[email protected]' -match '^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]{2,4}$' 

'patrick.gruenauer@outlookdomain' -match '^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]{2,4}$' 

希望这有帮助。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯