Forum Moderators: coopster & phranque

Message Too Old, No Replies

How to process every line in a string?

or how to get my regular expression working...

         

MichaelBluejay

5:39 am on Jan 1, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'd like to add a slash character to the beginning of each line in a string if it doesn't already have one. I tried this regex:

$allLinks =~ s¦^[^/](.)¦/$1¦g;

But that *replaces* the first character with a slash. And it only operates on the first line, even though I used the "g" option.

As an alternative I figured I could split the string into an array, then process each item in the array, and then join the array elements back into a string, but that seems like a duct-tape approach. I'd like to use the quick and professional version if possible.

Thanks for your help, -MBJ-

adni18

9:04 pm on Jan 2, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I can tell why it only treated the first line (I think)

1¦g;

should be

1/g;

SeanW

9:28 pm on Jan 2, 2005 (gmt 0)

10+ Year Member



Try mg at the end instead of g.

And it's replacing the first char because that's what you told it to do ;) $1 matches the second char:

^ - match beginning of line
[^/] - match first char if it's not a /
(.) - match second char and save in $1

You want the parenthesis around the [^/]

Sean

Sean

wruppert

6:00 pm on Jan 3, 2005 (gmt 0)

10+ Year Member



Sean is correct - here is the complete statement:

$allLinks =~ s¦^([^/])¦/$1¦mg;

MichaelBluejay

1:10 am on Jan 13, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks SeanW and wruppert, that works nicely. It not only works but now I can see the error in my ways (or at least my code).

One, I didn't have what I wanted to match in the parentheses, as you said.
Two, I didn't have the /m flag. I'd never seen that before, so I just looked it up, and found that it's the magic flag that makes a regular expression operate on multiple lines. Very handy. I thought /g was enough to do that (who would have thought that global doesn't really mean global), but now I know better.

adni18, you don't have to use a slash in a substitution expression. You can use any character you want. I use the bar character instead of a slash when the expression itself contains a slash, to make the expression easier to read.

SeanW

1:57 am on Jan 13, 2005 (gmt 0)

10+ Year Member



who would have thought that global doesn't really mean global

You wouldn't have run into this problem if you didn't need to anchor your regexp (^). Global does mean global, but "beginning of line" doesn't mean "beginning of line" ;)

Sean