Reputation: 5502
I'm trying to insert a comment character into a string something similar to this:
-CreateVideoTracker VT1 "vt name"
becomes
-CreateVideoTracker VT1 # "vt name"
The VT1 word can actually be anything, so I'm using the regex
$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g;
which gives me the result:
-CreateVideoTracker w #T1 "vt name"
Is there any way to do this with a single regex, or do I need to split up the string and insert the comment manually?
Upvotes: 2
Views: 6426
Reputation: 98398
You have two problems in:
$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g;
First, you want to match multiple character words, so in the left side, \w should be \w+. Second, you can't use patterns like \w on the right side; instead capture what you want on the left with () and put it on the right with $1, $2, etc.:
$line =~ s/\-CreateVideoTracker (\w+)/\-CreateVideoTracker $1 # /g;
Upvotes: 0
Reputation: 34130
You could use the \K
feature of Perl 5.10 regexs;
$line=~s/^\-CreateVideoTracker\s+\w+\K/ #/;
Upvotes: 2
Reputation: 339955
$line =~ s/^(\-CreateVideoTracker)\s+(\w+)/$1 $2 #/;
The bracketed expressions (known as "capture buffers") in the first half of the regexp are referenced as $1
, $2
. etc in the second half.
Upvotes: 9