我的文本多行,具有这样的结构。
Sentence a. Sentence b part 1 `r`n
sentence b part 2. Sentence c.`r`n
Sentence d. Sentence e. Sentence f. `r`n
....
我想将这些句子和部分提取到每个部分或一个句子的单个字符串数组中。 到目前为止,我发现了这些东西。
第一种方式。
$mySentences = $lineFromTheText -split "(?<=\.)"
第二种方式。
$mySentences = [regex]::matches($lineFromTheText, "([^.?!]+[.?!])?([^.?!]*$)?") | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}
第三个代码。
$mySentences = ($lineFromTheText | Select-String -Pattern "([^.?!]+[.?!])?([^.?!]*$)?" -AllMatches).Matches | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}
似乎所有这些代码对我来说都像我期望的那样执行相同的操作,但是我不知道自己在这些方法中应该使用哪种方式。我的意思是最好的代码是什么。 请告诉我知道。 谢谢。
答案 0 :(得分:2)
如果您需要最少的执行时间,则可以进行测量。让我们每个解决方案运行10000次,看看需要多长时间:
$lineFromTheText = "Sentence d. Sentence e. Sentence f."
(Measure-Command {1..10000 | % {$mySentences = $lineFromTheText -split "(?<=\.)"}}).Ticks
(Measure-Command {1..10000 | % {$mySentences = [regex]::matches($lineFromTheText, "([^.?!]+[.?!])?([^.?!]*$)?") | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}}}).Ticks
(Measure-Command {1..10000 | % {$mySentences = ($lineFromTheText | Select-String -Pattern "([^.?!]+[.?!])?([^.?!]*$)?" -AllMatches).Matches | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}}}).Ticks
输出(示例):
1059468
14512767
20444350
第一个解决方案似乎是最快的,而第三个解决方案是最慢的。