【发布时间】:2026-01-05 20:10:02
【问题描述】:
我有很多行的文本,结构是这样的。
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 "")) {$_}}
似乎所有这些代码对我的作用与我所期望的一样,但我想知道自己在这么多这些方式中应该使用哪些代码。我的意思是什么是最好的代码。 请告诉我知道。 谢谢。
【问题讨论】:
-
“最佳代码”取决于您未提供的指标。您想要最短的执行时间吗?最少字节的源代码?最好的人类可读代码?最少的内存使用?他们都是?如果是这样,哪个指标应该具有哪个权重?
-
根据KISS,你会选择第一个解决方案;-)
-
性能效率怎么样
-
仍然模棱两可,CPU 性能与内存性能?如果您正在寻找最快的方法,请参阅下面的答案。
标签: string powershell text-extraction