【问题标题】:Powershell - Difference results between "string" -split and "string".split() without loosing separatorPowershell - “string” -split 和 “string”.split() 之间的差异结果没有丢失分隔符
【发布时间】:2020-10-21 12:14:24
【问题描述】:

我正在尝试从字符串中拆分句子。我在 Stack Overflow 上找到了这个:

$stringToExtract = "sentence a. sentence b. sentence c. last phrase"
$mySentences = $stringToExtract -split "(?<=\.)"
$mySentences
sentence a.
 sentence b.
 sentence c.
 last phrase

但是……

$stringToExtract = "sentence a. sentence b. sentence c. last phrase"
$mySentences = $stringToExtract.split("(?<=\.)")
$mySentences
sentence a
 sentence b
 sentence c
 last phrase

...不同的结果。

我想使用代码 $mySentences = $stringToExtract.split("(?&lt;=\.)")。有人请告诉我这件事出了什么问题。 谢谢。

【问题讨论】:

  • -split 是一个使用正则表达式的运算符。 (?&lt;=\.). 字符的正则表达式正向回溯。它不消耗任何字符,这就是为什么 . 在拆分后仍然存在的原因。在不使用正则表达式的.split() 方法中,只是将所有这些字符视为要分割的字符。因为. 是你的字符串中唯一的一个,所以它是唯一一个分裂的。
  • -split-match-replace 等其他运算符使用正则表达式,而 .match .replace.split 不使用正则表达式。
  • 另外,如果您对.split() 方法的结果感到满意,为了简洁起见,只需将其缩减为.split('.')
  • 感谢所有 cmets。非常感谢。
  • @AdminOfThings 如果它们真的是一个句子,我想在句子末尾保留点。顺便说一句,我正在从字符串中提取句子。

标签: string powershell split


【解决方案1】:

-split 是一个使用正则表达式的运算符。 (?&lt;=\.). 字符的正则表达式正向回溯。它匹配紧跟其后有. 字符的位置。但由于它不消耗任何字符,因此在拆分后不会删除任何字符,包括.

String.Split() 方法不使用正则表达式,将所有这些字符视为要分割的字符数组。这意味着它将在(?&lt;=\.) 处拆分。因为. 是唯一一个在你的字符串中匹配的,所以它是唯一一个分裂的。由于String.Split() 确实会消耗字符,因此您的拆分字符将被删除。

为了获得理想的结果,我建议坚持使用-split。没有理由不使用它。

$stringToExtract = "sentence a. sentence b. sentence c. last phrase"
$mySentences = $stringToExtract -split "(?<=\.)"

或者,如果使用更美观的方法,您可以使用Regex.Split() 方法获得相同的效果。

$mySentences = [regex]::Split($stringToExtract,'(?<=\.)')

【讨论】:

  • 嘿。你能帮我建立一个正则表达式来从行中提取这个句子部分:"From a starry sky a wide view descends to a magnificent castle with a ..." 最后有n dot:一、二、...........,我想把它们都包括在内。我尝试了$mySentences = [regex]::Split($stringToExtract,'(?&lt;=(\.+?)'),但没有成功。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
  • 2014-02-24
  • 2018-07-09
  • 2018-03-17
  • 1970-01-01
相关资源
最近更新 更多