描述
在这里,我使用了两个单独的表达式,第一个提取所有标题大小写的单词,其中单词连续包含 2 个或更多单词。第二个表达式提取每个单词的第一个字母......使用逻辑将它们缝合在一起以替换源字符串中的值。
(?:^|\s+)((?:\s*\b[A-Z]\w{1,}\b){2,})
\b([A-Z])
例子
$Regex = '(?:^|\s+)((?:\s*\b[A-Z]\w{1,}\b){2,})'
$String = 'I went to the Annual General Meeting with some guy named Scott Jones on Perl Compatible Regular Expressions. '
Write-Host start with
write-host $String
Write-Host
Write-Host found
$Matches = @()
([regex]"$Regex").matches($String) | foreach {
$FoundThis = $_.Groups[1].Value
write-host "group one $($_.Groups[1].Index) = '$($FoundThis)'"
[string]$Acronym = ""
([regex]"\b([A-Z])").matches($FoundThis) | foreach {
$Acronym += $_.Groups[1].Value
} # next match
$String = $String -replace $FoundThis, $Acronym
} # next match
Write-Host $String
产量
start with
I went to the Annual General Meeting with some guy named Scott Jones on Perl Compatible Regular Expressions.
found
group one 14 = 'Annual General Meeting'
group one 57 = 'Scott Jones'
group one 72 = 'Perl Compatible Regular Expressions'
I went to the AGM with some guy named SJ on PCRE.
免责声明
- 是的,我知道 OP 要求提供 python 示例,但我更熟悉 powershell。逻辑是一样的。
- 如前所述,这将匹配专有名称,并且如果句子的第一个单词恰好是标题大小写,然后是标题大小写的第二个单词。所以你需要自己做错误检查