foreach ($line in $test) {
$line.GetType()
$newline = $line -split ("<.*?>") -split ("{.*?}") # remove html and css tags
$newline.GetType()
}
我在嘗試使用該.Trim()方法時遇到了這個問題$newline。它有效,但智能感知并沒有表明它會起作用。我原以為.Trim()只適用于字串物件 (BaseType:System.Object),但在這種情況下,它似乎也適用于 String[] 物件 (BaseType:System.Array)。
$line.GetType() 回報
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
$newline.GetType() 回報
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String[] System.Array
首先,我想知道為什么我的原始字串被轉換為一個陣列,假設它是...的回傳值-split現在是一個字符陣列嗎?我有點困惑。
其次,如果有一個好的答案,為什么字串方法在技術上是一個陣列?
來自 Python 和 C/C ,謝謝。
uj5u.com熱心網友回復:
Lasse V. Karlsen已經提供了關鍵資訊來理解為什么字串( $line)string[]在被拆分后會被轉換成這樣。在這種情況下,您最有可能想要使用的是與正則運算式兼容的-replace運算子。
以下面為例:
$htmlcss = @'
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<h2>HTML Table</h2>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
</table>
</body>
</html>
'@
使用-replace洗掉 HTML 和 CSS 標簽然后-split獲取string[]并最后過濾陣列以跳過空行:
$htmlcss -replace '(?s)<.*?>|\{.*?\}' -split '\r?\n' |
Where-Object { $_ -match '\S' }
結果是:
table
td, th
tr:nth-child(even)
HTML Table
Company
Contact
Country
Alfreds Futterkiste
Maria Anders
Germany
請注意,對于\{.*?\}此正則運算式,您必須將其與string或multi-line string 一起使用。它不適用于字串陣列 string[]。您還需要啟用該(?s)標志。假設您正在從一個檔案中讀取此內容,您將希望-Raw在Get-Content.
uj5u.com熱心網友回復:
Santiago Squarzon 的有用答案為您的代碼嘗試執行的操作提供了有效的解決方案。
根據Lasse V. Karlsen的有用評論回答您提出的問題:
我想知道為什么我的原始字串被轉換為陣列,假設它是-split的回傳值...現在是字符陣列嗎?
該-split運算子通過給定的分隔符正則運算式將字串或字串數??組拆分為子字串,并將子字串作為字串陣列( [string[]])
'foo|bar' -split '\|' # -> [string[]] ('foo', 'bar')
以陣列作為輸入,對每個元素分別執行拆分操作,并將每個元素的結果陣列連接起來形成一個單一的平面陣列。
'foo|bar', 'baz|quux' -split '\|' # -> [string[]] ('foo', 'bar', 'baz', 'quux')
其次,如果有一個好的答案,為什么字串方法在技術上是一個陣列?
您所看到的是半官方稱為成員列舉的功能:訪問集合上的成員(屬性或方法)并將其隱式應用于其每個元素的能力,結果收集在陣列(用于兩個或多個元素)。
在這個答案中有詳細描述。
至于給功能一個正式名稱:在撰寫本文時,它被描述,但沒有在概念幫助主題中命名。GitHub 檔案問題 #8437要求給它一個正式名稱。
about_Properties
快速示例:
# .Trim() is called on *each element* of the input array.
PS> (' foo', 'bar ').Trim() | ForEach-Object { "[$_]" }
[foo]
[bar]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399713.html
上一篇:將陣列與唯一鍵映射在一起
