PowerShell 正则表达式匹配字符串的开头

Dar*_*te1 5 regex powershell

有一个正则表达式可以完全满足我的要求,但我希望它能够仅检查字符串的开头,而不查看其后面的内容。

工作正则表达式:

[RegEx]$RegEx = "(.+?) (.+?)-(.+?)-(.+?)$"
Run Code Online (Sandbox Code Playgroud)

失败的尝试:

[RegEx]$RegEx = "^((.+?) (.+?)-(.+?)-(.+?))"
[RegEx]$RegEx = "\A(.+?) (.+?)-(.+?)-(.+?)"
Run Code Online (Sandbox Code Playgroud)

例子:

# Ok:
BEL Green-Fruit-Appel Stuff
BEL Green-Fruit-Appel Other stuff stuff

# Not ok (without anything):
BEL Green-Fruit-Appel            
Run Code Online (Sandbox Code Playgroud)

更多信息请点击此处

感谢您的帮助。

Kei*_*ill 5

放弃$并使用^

C:\PS> 'BEL Green-Fruit-Appel' -match '^(.+?) (.+?)-(.+?)-(.+?)'
True

C:\PS> $matches
Name                           Value
----                           -----
4                              A
3                              Fruit
2                              Green
1                              BEL
0                              BEL Green-Fruit-A
Run Code Online (Sandbox Code Playgroud)

最后一个捕获组只是A因为您使用的是非贪婪?所以它在第一个字符之后停止。如果您想要整个单词,请将最后一个捕获组更改为“-(\w+)”。