If your regex flavor supports lookarounds, this can be done with a simple regex-replace. Since lookaheads do not advance the position of the regex engine's cursor, we can use them to look for multiple patterns somewhere after one particular position. We can capture all these findings and write them back in the replacement string. To make sure that all of them are optional we could simply use ?
, but in this case, I'll add an empty alternative to the lookahead - this is necessary to trick the engine when it's backtracking. The pattern could then look like this:
^Name,(?=.*([(]W[)]\d+)|)(?=.*([(]H[)]\d+)|)(?=.*([(]M[)]\d+)|)(?=.*([(]P[)]\d+)|).*
The .*
at the end is to make sure that everything gets removed in the replacement.
And the replacement string like this:
Name,$1,$2,$3,$4
Here is a working demo using the ECMAScript flavor. It's a rather limited flavor, so this solution should be adaptable to most environments.