String Powershell';s-匹配与标点符号

String Powershell';s-匹配与标点符号,string,powershell,match,String,Powershell,Match,我正在尝试在Powershell中编写一个函数,用于测试字符串是否以标点符号结尾。现在,该方法如下所示: function ends_in_punctuation #Tests whether or not a word ends in punctuation { param([string]$WordToTest) #Takes string to check ending of $CharToCheck = $WordToTest[$WordToTest.Length - 1

我正在尝试在Powershell中编写一个函数,用于测试字符串是否以标点符号结尾。现在,该方法如下所示:

function ends_in_punctuation #Tests whether or not a word ends in punctuation
{
    param([string]$WordToTest) #Takes string to check ending of
    $CharToCheck = $WordToTest[$WordToTest.Length - 1] #Getting last character of string
    $Punctuation = ".?!" #Ending punctuation in english
    If($Punctuation -match $CharToCheck) #If last character is punctuation
    {
        $true #return true
    }
    Else
    {
        $false #return false
    }
}
如果单词以句号或感叹号结尾,效果会很好,但如果单词以问号结尾,则会抛出此错误

[ERROR] parsing "?" - Quantifier {x,y} following nothing.
[ERROR] At D:\...\PigLatin.ps1:24 char:5
[ERROR] +     If($Punctuation -match $CharToCheck) #If last character is punctu ...
[ERROR] +        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[ERROR]     + CategoryInfo          : OperationStopped: (:) [], ArgumentException
[ERROR]     + FullyQualifiedErrorId : System.ArgumentException
[ERROR]  

不知道为什么。我是PowerShell的新手,因此我将非常感谢您的帮助,谢谢

首先,操作数是反向的
-match
在左侧接受字符串(或集合),在右侧接受正则表达式

此外,由于
-match
接受一个正则表达式,因此您在那里尝试匹配的字符串是非常错误的,根本不会执行您想要的操作。目前它的意思是»匹配任何包含感叹号的字符串,前面有任何字符(但即使没有字符,也可以)«

正则表达式应该使用字符类作为标点;这也巧妙地解决了
是正则表达式中的特殊字符的问题:

[.?!]
因此,总而言之,您可能需要以下内容:

$CharToCheck -match '[.?!]'
另一个选项是检查字符串的最后一个字符是否在标点符号字符串中:

$Punctuation.Contains($CharToCheck)

或者对整个字符串使用正则表达式匹配(此处的正则表达式锚定到字符串的末尾):

获取最后一个字符也可以通过

$WordToTest[-1]

PowerShell在这里比C#好一点。

这不是
-match
倒过来的吗?你不想把图案放在右边吗?或者,数组和
-contains
在这里不是更好吗?您的问题是
-match
的右侧是一个正则表达式,
是一个元字符,它不能单独存在而不被转义。这解决了我的问题,非常感谢您的代码和详细解释!
$WordToTest -match '[.?!]$'
$WordToTest[-1]