tags:

views:

1151

answers:

4

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?

+8  A: 
$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.

Alnitak
A: 
(?<=-CreateVideoTracker\s[^\s]*)(?<replacemelolkthx>\s)

replace with " # "

Will
Crap, wrong language
Will
That's ok, I didn't specify that it had to be Perl
bsruth
+1  A: 

You could use the \K feature of Perl 5.10 regexs;

$line=~s/^\-CreateVideoTracker\s+\w+\K/ #/;
Brad Gilbert
A: 

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;
ysth