* Powershellの-matchで文字列正規表現での部分文字列を取得,(?<>?)の名前付けではまったが理解が深まった

:CATEGORIES: Powershell,正規表現


PS D:\> $str
2002-12-29_163215_告発事件一件記録(写真資料・撮影日時).jpg

PS D:\> $Str
2002-12-29_163215_告発事件一件記録(写真資料・撮影日時).jpg

PS D:\> $Str -match "_[^\.]+"; $Matches
True

Name Value

        • -----

0 _告発事件一件記録(写真資料・撮影日時)



PS D:\>
PS D:\> $str -match "(?_[^\.]+?)"; $Matches
True

Name Value

        • -----

name _告
0 _告



PS D:\> $str -match "(?_[^\.]+?)"; $Matches["name"]
True
_告

PS D:\> $str -match "(?_[^\.]+?)"; $Matches["fname"]
True
_告

PS D:\> $Str -match "_[^\.]+"; $Matches
True

Name Value

        • -----

0 _告発事件一件記録(写真資料・撮影日時)



PS D:\> $str -match "(?....-..-.._......?)"; $Matches["fname"]
True
2002-12-29_163215

PS D:\> $str -match "(?_[^\.]+)"; $Matches["fname"]
True
_告発事件一件記録(写真資料・撮影日時)

PS D:\> $Str -match "(?:....-..-.._......_)(.+)(?:\.jpg)"; $Matches
True

Name Value

        • -----

1 告発事件一件記録(写真資料・撮影日時)
0 2002-12-29_163215_告発事件一件記録(写真資料・撮影日時).jpg



PS D:\> $Matches[1]
告発事件一件記録(写真資料・撮影日時)

PS D:\>

 きっかけは,次のページの次のコードが気になり,調べたのが始まりでした。「"(?_[^\.]+?)"」では何度やってもうまく行かず,最長一致のはずの+が最短一致となっていました。


function script:makeFolderName($originalSatsueiDate){
$folderName = ""

if($originalSatsueiDate -eq $null -or $originalSatsueiDate.length -lt 1){
return $folderName
}

# yyyy.mm.ddを抽出しyyyy-mm-ddに変換
if($originalSatsueiDate -match "(?\d\d\d\d.\d\d.\d\d?)"){
$folderName = $Matches["SatsueiDate"].replace(":","-")
return $folderName
}else{
return $folderName
}
}

[source:]Exifの撮影日時からフォルダを作成して画像をコピーする - 管理人Kのひとりごと https://www.k-hitorigoto.online/entry/2017/09/23/124528

 疑問が解決できたのは次のページの次の部分になりますが,?を末尾につけて囲んだ場合の挙動は情報が見当たりませんでした。とりあえず,先頭にのみ?をつけた場合に,期待通りの結果が得られました。


(?subexpression)
キャプチャした部分式に名前を指定できる。

PS>"PowerShell" -match '(?o.e)r(?S.e)ll';$matches
True

Name                           Value

        • -----

second                         She
first                          owe
0                              owerShell


PS>$matches.second
She

[source:]PowerShell: ◆正規表現の基礎<グループ化構成体> http://mtgpowershell.blogspot.com/2011/12/blog-post_23.html