2016-01-28 30 views
2

我有這個文本文件:正則表達式正在Regex101而不是內部PowerShell的

[Tabs] 
MAILBOXSEND=1 
MAILBOX=8 
USERS=6 
DOCUMENTS_Q=9 
MED_WEBSERVCALLS_LOA=3 
FCLMNA=1 
INCZOOMFORM=1 
USERSB=1 
USERSB_ONE=1 
DATAPRIV=1 
MED_WEBSERVCALLS=2 
TINVOICES=1 
PORDERS=9 
PORDERSTOTAL=1 
LOGPART=1 
LOGCOUNTERS=1 
PARTMSG=1 
[External Mail] 
Send=Y 
Hostname=Server 
Domain=Domain 
[email protected] 
MyName=My Test 
Port=25 
SSL=0 
[Search] 
SUPPLIERS=5,1 
StartButton=1 
Ignore Case=0 
PART=6,1 

我試圖捕捉到下一個支架[]集團[External Mail]之間的所有文字,

我有這個正則表達式這做的工作,在Regex101測試,畢竟測試的,我發現它不是內部PowerShell的工作:

$Text = Get-Content c:\text.txt 
$Text -match '(?s)(?<=\[External Mail\]).*?(?=\[.*?\])' 
or: 
$Text | Select-String '(?s)(?<=\[External Mail\]).*?(?=\[.*?\])' 

沒有返回

你知道我錯過了什麼嗎?

感謝

+0

你有沒有保護你的'\'? –

+0

我不會爲此使用正則表達式。您可以自己轉換爲對象,也可以使用[Get-INIContent](http://blogs.technet.com/b/heyscriptingguy/archive/2011/08/20/use-powershell-to-work-with -any-INI-file.aspx)。感謝您添加您的代碼。 – Matt

回答

3

既然你試圖讓你需要的工作對一個多串多行正則表達式匹配。這就是你的兩種regex101和PowerShell的區別。 Get-Content將返回一個字符串數組。你的正則表達式不匹配任何東西,因爲它只是在文件內的單行上進行測試。

的PowerShell 2.0

$Text = Get-Content c:\text.txt | Out-String 

的PowerShell 3.0的高

$Text = Get-Content c:\text.txt -Raw 

正如我說我的意見,你並不真的需要正則表達式,以這種方式,對於這種類型的字符串的提取。 There are scripts that already exist to parse INI content。如果您打算替換內容,則必須假設合作伙伴cmdlet Out-INIContent存在,但我確信有人提供了它。 vonPryz's answer包含有關該cmdlet的更多信息

+0

你只是忍者 - 添加.iI解析器鏈接我很高興炫耀:-P – vonPryz

+0

@vonPryz是啊...我在我之前的評論中已經提到了它,但它作爲答案的一部分會更好。 – Matt

+0

@JustCurious我告訴你我的回答如何?我解釋瞭如何解決你的問題。我還沒有測試過你的正則表達式,但.....它仍然不起作用 – Matt

4

看起來像是在解析.INI文件。不要試圖再次發明輪子,從existing code採取槓桿作用。該解決方案將.Ini文件作爲易於使用的嵌套散列表讀取。

在鏈接腐的情況下,這裏是從腳本專家存檔功能:

function Get-IniContent ($filePath) 
{ 
    $ini = @{} 
    switch -regex -file $FilePath 
    { 
     "^\[(.+)\]" # Section 
     { 
      $section = $matches[1] 
      $ini[$section] = @{} 
      $CommentCount = 0 
     } 
     "^(;.*)$" # Comment 
     { 
      $value = $matches[1] 
      $CommentCount = $CommentCount + 1 
      $name = "Comment" + $CommentCount 
      $ini[$section][$name] = $value 
     } 
     "(.+?)\s*=(.*)" # Key 
     { 
      $name,$value = $matches[1..2] 
      $ini[$section][$name] = $value 
     } 
    } 
    return $ini 
} 

# Sample usage: 
$i = Get-IniContent c:\temp\test.ini 
$i["external mail"] 

Name       Value 
----       ----- 
Domain       Domain 
SSL       0 
Hostname      Server 
Send       Y 
MyName       My Test 
Port       25 
Myemail      [email protected] 

$i["external mail"].hostname 
Server 
+0

任何簡單的方法來取代一個完整的部分?或者只是創建一個包含所有細節(foreach或其他)的新項目? – JustCurious