这段代码运行良好
$pop = New-Object -ComObject wscript.shell
$string = "John Adams, Age: 204, Email: [email protected]"
# Regular expression pattern with named groups
$regex = '(?<Name>\w+\s\w+),\sAge:\s(?<Age>\d+),\sEmail:\s(?<Email>[^\s]+)'
# Apply the regex match
if ($string -match $regex) {
# Access the groups using automatic variable $matches
$name = $matches['Name']
$age = $matches['Age']
$email = $matches['Email']
$pop.popup("Name: $name`nAge: $age`nEmail: $email",5,"Success",4096)
} else {
$pop.popup("No Matches found.",4,"Oh Oh",4096)
}
Exit
但是如果我将字符串改为以 John Quincey Adams 开头,名称组只会返回 Quincey Adams。我知道可以添加一个额外的 \w+\s,但是有没有办法以通用的方式将任意数量的单词名称捕获到组中?
(?:\s\w+)*
您可以在捕获组中添加一个可选的非捕获组Name
,请参阅:https://regex101.com/r/itimND/1。也许如果通过拆分来解析字符串会更容易: