【问题标题】:Get text between two characters获取两个字符之间的文本
【发布时间】:2019-10-10 07:23:03
【问题描述】:

我有一个如下所示的纯文本文件:

"sample1@gmail.com"
"sample2.test@gmail.com"
"sample3.test.test2@gmail.com"

等等……

现在使用 Powershell 我正在尝试逐行读取此纯文本文件并读取不带双引号的电子邮件并将其添加到数组列表中:

$arrayListEmails = New-Object System.Collections.ArrayList

$regex = '"([^/)]+)"'
[System.IO.File]::ReadLines("C:\temp\emailsList.txt") | Where-Object {$_ -match $regex} | ForEach-Object {
    write-host "email: $_"
    $arrayListEmails.Add($_) > $null
}

我不知道为什么,但在执行上述代码块后,我收到带有双引号的电子邮件,这是输出:

email: "sample1@gmail.com"
email: "sample2.test@gmail.com"
email: "sample3.test.test2@gmail.com"

等等……

但我想要以下内容(不带双引号的电子邮件):

email: sample1@gmail.com
email: sample2.test@gmail.com
email: sample3.test.test2@gmail.com

似乎正则表达式被带上了双引号......

【问题讨论】:

  • 如果您在每一行上使用.Trim('"'),您将获得 没有 修剪字符串中的前导/尾随字符的行。在这种情况下,它将删除前导和尾随双引号。 [咧嘴]

标签: regex powershell powershell-2.0 regex-greedy


【解决方案1】:

有一种非常简单的方法可以清除字符串中的前导字符和尾随字符。使用.Trim() 字符串方法。 [grin] 它将从目标字符串的末尾删除修剪列表中的每个字符。

# fake reading in a text file
#    in real life, use Get-Content
$InStuff = @'
"sample1@gmail.com"
"sample2.test@gmail.com"
"sample3.test.test2@gmail.com"
'@ -split [System.Environment]::NewLine

$DeQuotedEmailList = foreach ($IS_Item in $InStuff)
    {
    # the trim string is <single><double><single> quotes
    #    it will remove any leading and/or trailing double quotes
    $IS_Item.Trim('"')
    }

$DeQuotedEmailList

输出...

sample1@gmail.com
sample2.test@gmail.com
sample3.test.test2@gmail.com

【讨论】:

    【解决方案2】:

    也许这个正则表达式可以帮助你:

    "([^/\)]+?)"
    

    您必须使用组$1 来获得您想要的值。那是没有引号的电子邮件。

    【讨论】:

      【解决方案3】:

      您也可以这样做(import-csv 删除列上的双引号):

      $Yourlist=import-csv "C:\temp\emailsList.txt" -Header Email
      $Yourlist | %{ "email : {0}" -f $_.Email }
      

      【讨论】:

      • 我喜欢这个解决方案。无需使用额外的功能,如修剪、替换...
      【解决方案4】:

      因为你的电子邮件有报价:) 试试这个

      write-host ("email: " + $_.Replace('"', ""))
      $arrayListEmails.Add($_.Replace('"', "")) > $null
      

      【讨论】:

      • 是的,我的电子邮件在纯文本文件中有引号。出于这个原因,我使用正则表达式从每封电子邮件的开头和结尾消除它们,然后再将其存储在数组列表中,但似乎正则表达式也获取引号而不是忽略它们。
      • 您的正则表达式(如果它是正确的)不会消除引号,而是仅过滤您的列表,然后您的电子邮件将出现在您的最终列表中
      猜你喜欢
      • 2023-02-13
      • 1970-01-01
      • 2018-11-02
      • 2013-04-02
      • 2014-10-03
      • 2019-07-02
      • 1970-01-01
      • 2017-01-07
      • 2017-06-16
      相关资源
      最近更新 更多