Reputation: 1047
I have a line that reads like this.
NAME: ^?^?^, DOB: ^?^?^?^?, SN: ^?^?
For reasons beyond my control, non-printing characters are showing up in the file. For this, I just need to match and remove ONLY the ones appear after NAME, DOB, and SN.
So I am testing out the code with NAME, and this is my regex
$_ =~ s/(?:NAME: )[^[:print:]]//g)
The expected output is:
NAME: ,
However, I am getting:
^?^?^,
With name stripped instead? Does non-capturing not work in substitution?
Upvotes: 1
Views: 192
Reputation: 1364
Non-capturing groups are for when you want to avoid the overhead involved in capturing, or when you want to keep unnecessary things out of your capture groups while still being able to group them. To keep something in a substitution you could do
$_ =~ s/(NAME:)\P{print}+/$1/g;
which will capture Name: and substitute it back in, or use the \K (keep) metacharacter:
$_ =~ s/NAME:\K\P{print}+//g;
which prevents s/// from substituting anything left of it in the pattern.
Side note: s/// operates on $_ unless a variable is specified with =~, so $_ =~ s/// is redundant (but some might argue it conveys intent).
Upvotes: 1