Quick Regex Subst question

M

Marv

Hello,

I'm new to regex and hoping someone can give me a quick answer to this
question as I can't seem to find it anywhere.

I'm trying to parse a line and subsitute any one charactor followed by
a $ and surrounded by a front slash on both sides with the same
charactor followed by a space and "(Drive)". This also must occur at
the beginning of the line. So basically substitute "$" for "(Drive)".

Ex.

/C$/path/path/

ends up as:

/C (Drive)/path/path

I've got the following so far:

$test = '/C$/path/path/';

$test =~ s/^\/.\$/\/.\(Drive\)/;

But when I do: printf "$test\n";

I get:

/.(Drive)/account/test/

I know the dot is wrong, but how do I carry the "C" over in the
substituion.

Thanks in advance.

Marv
 
B

Ben Morrow

Marv said:
Hello,

ends up as:

/C (Drive)/path/path

I've got the following so far:

$test = '/C$/path/path/';

$test =~ s/^\/.\$/\/.\(Drive\)/;

Bleech! Use some other delimiter to avoid all those backwhacks. Use /x
to clean things up a bit. The second half of an s/// is not a regex,
just a double-quotey string, so () don't need escaping.

$test =~ s|^/ (.) \$ /|/$1 (Drive)/|x;

See perldoc perlretut "Extracting matches" for how the () abd the $1
join up.

I would be tempted to use look{ahead,behind} here, just because it
feels cleaner; viz.:

$test =~ s|(?<= ^/) (.) \$ (?= /)|$1 (Drive)|x;

but it's probably too complex to be worth bothering with here.
But when I do: printf "$test\n";

Don't use printf when you men print. I don't think I have ever used
printf in perl... even when it would be useful, I instinctively use
'print sprintf ...' instead :).

Ben
 
E

Eric Amick

I'm trying to parse a line and subsitute any one charactor followed by
a $ and surrounded by a front slash on both sides with the same
charactor followed by a space and "(Drive)". This also must occur at
the beginning of the line. So basically substitute "$" for "(Drive)".

Ex.

/C$/path/path/

ends up as:

/C (Drive)/path/path

I've got the following so far:

$test = '/C$/path/path/';

$test =~ s/^\/.\$/\/.\(Drive\)/;

If you surround a portion of a regex with parentheses, you can refer to
the text it matches with $1 later.

$test =~ s!^/(.)\$/!/$1 (Drive)/!;

Note that you can use just about any character to surround the regex and
substitution string, which makes working with slashes a lot less
painful.

See perldoc perlretut, particularly the section called "Extracting
Matches".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top