0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Powershell Regular Expression 返信~改行の連続を切る正規表現 ^title ...Enter multiple

Posted at

前提

以下の文字列を返信~改行ごとに切る
返信先は含まれる
Dドライブのルートにテキストファイルで出力する

$str = @"
返信  1/23(水) 12:24
返信先:

ice

返信 1/23(水) 12:24
返信先:教えて
おじちゃん \CE@a

返信  1/23(水)  12:24
返信先:@t 無い
T☮️@mo

返信 
返信先:@_A他1人 そういうことをには

か@Yk

返信 1/23(水)  12:24
返信先:@t べき
い@b

"@
$rex = New-Object regex "^返信[^先].*\s.*?[\s.*?]{1,}\s.*?\s\s$",("Multiline","IgnoreCase")
$ret=$rex.Matches($str);$ret.Count;$ret[0].Groups.Count
$ret[0].Value -replace("\<.*?\>","")
if($ret.Count -gt 0 ){
$sFullPath = (Join-path $folder ((Get-Date -f s) -replace '[-T:]','')) ;
$sFullPath =$sFullPath + '.txt'
$ret | foreach{ $_.value  | Out-File $sFullPath -Append -Encoding "utf8"}}

ポイント

MultilineオプションはNew-Objectでつける

そうでないとエラーになるらしい

改行が複数ある場合は繰り返し記号が効かない部分が出る

[.*?\s.*?\s]{1,}は冗長性を確保する
そうしないと

返信 
返信先:@_A他1人 そういうことをには

か@Yk

こういう場合が完全に拾えない。

このロジックは

ある文字から始まるが、同様の文字では切らず、末尾が若干揺れていても吸収する、ということになる正規表現である。

参考

Windows PowerShell 初心者プログラミング
Select-Stringを使って行単位で取得する。しかし今回は複数行なので使えない。

regexのMatchメソッド落とし穴 PowerShell Scripting Weblog 2008/02/03

うむ…別なオーバーロードにキャストしようとして失敗してるな。どうすればいいんだろう?
とりあえずオプション使いたかったらコンストラクタ指定ですかねー。

オンラインで正規表現をテスト

https://regex101.com/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?