Seiji Amasawa
Seiji Amasawa

Reputation: 29

Regex PowerShell: Replace every comma with [blank] if it doesn't have a value in between a comma

Regex PowerShell: Replace every comma with [blank] if it doesn't have a value in between a comma.

Raw Data:

Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported
Name 2,Exported,Exported,Exported,Exported,Exported,Exported,
Name 3,Exported,Exported,,Exported,Exported,,

Expected Output:

Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported
Name 2,Exported,Exported,Exported,Exported,Exported,Exported,[Blank]
Name 3,Exported,Exported,[Blank],Exported,Exported,[Blank],[Blank]

This is what I got so far:
```powershell
$data -replace ("(,\W)|(,\s)", ",[Blank],")

However, it doesn't work as intended.

Upvotes: 0

Views: 101

Answers (1)

The fourth bird
The fourth bird

Reputation: 163632

As a pattern, you could use

(?m),[^\S\r\n]*(?=,|$)

Explanation

  • (?m) Inline multiline modifier
  • , Match a comma
  • [^\S\r\n]* Match 0+ times a whitespace char without a newline
  • (?=,|$) Positive lookahead, assert what is at the right is either a comma or the end or the line

And replace with

,[Blank]

.NET regex demo | Powershell demo

enter image description here

For example

$data=@'
Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported

Name 2,Exported,Exported,Exported,Exported,Exported,Exported,

Name 3,Exported,Exported,,Exported,Exported,,
'@
$data -replace ("(?m),[^\S\r\n]*(?=,|$)", ",[Blank]")

Output

Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported

Name 2,Exported,Exported,Exported,Exported,Exported,Exported,[Blank]

Name 3,Exported,Exported,[Blank],Exported,Exported,[Blank],[Blank]

Upvotes: 3

Related Questions