Powershell:指定电子邮件:密码,中间有随机数据

问题描述

类似这样 - Extract email:password

但是我们这里的情况是,在某些文件中,我要解析的数据之间还有其他数据,例如:

email:lastname:firstname:password 或 email:lastname:firstname:dob:password

所以我的问题是 - 使用哪个命令可以忽略 2 个部分,例如“lastname:firstname”或什至 3 个部分“lastname:firstname:dob”。我正在使用以下正则表达式从大列表中检索 email:password。

$sw = [System.IO.StreamWriter]::new("$PWD/out.txt")

switch -regex -file in.txt { 
   '(?<=:)[^@:]+@[^:]+:.*' { $sw.WriteLine($Matches[0]) } 
}

$sw.Close()

解决方法

您需要完善您的正则表达式:

# Create sample input file
@'
...:foo@example.org:password1
...:bar@example.org:lastname:firstname:password2
...:baz@example.org:lastname:firstname:dob:password3
'@ > in.txt

# Process the file line by line.
switch -regex -file in.txt { 
  '(?<=:)([^@:]+@[^:]+)(?:.*):(.*)' { '{0}:{1}' -f $Matches[1],$Matches[2] } 
}

为简洁起见,上面省略了将输出保存到文件中,因此提取的电子邮件密码对默认打印到屏幕上,即:

foo@example.org:password1
bar@example.org:password2
baz@example.org:password3

正则表达式说明:

  • (?<=:) 是一个肯定的后视断言,用于确保匹配在 : 字符之后开始。

  • ([^@:]+@[^:]+) 使用捕获组(捕获子表达式,(...))来匹配直到但不包括下一个 : 的电子邮件地址。

  • (?:.*): 使用无条件匹配零个或多个字符 ((?:...)) 的非捕获子表达式 (.*) 后跟 :

  • (.*) 使用捕获组来捕获每行中有效最后 : 之后的所有剩余字符,假定为密码。>

  • $Matches[1]$Matches[2] 指的是第一个和第二个捕获组匹配项,即电子邮件地址和密码。

,

假设你有这样的数据:

"lastname:firstname" 
"lastname:firstname:dob"
"lastname:firstname:password:somepassword" 
"lastname:john:firstname:jacob:password:dingleheimershmit

您可以像这样在每一行中移动:

$items = gc .\stack.txt

ForEach($item in $items){

}

然后我们可以将每一行拆分为一个 : 字符,并检查每行是否与字符串 passwrod 匹配。如果是,那么我们检查该行中应该是密码的下一个令牌。

此代码将助您一臂之力,您只需要使用 $password 做一些有意义的事情。

$items = gc .\stack.txt

ForEach($item in $items){
    "processing $item"
    $tokens = $item.Split(":")
    For($x=0; $x -lt $tokens.Count;$x++){
        $token = $tokens[$x]
        
        #"Checking if $token is like password"
        if ($token -match "password"){
            "since this token is like password,checking next token which should be a password"
            $password = $tokens[$x+1]
            Write-Host -ForegroundColor Yellow $password
        }            
    
    }
}


enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...