homepage Welcome to WebmasterWorld Guest from 54.227.11.45
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
Forum Library, Charter, Moderators: coopster & jatar k & phranque

Perl Server Side CGI Scripting Forum

    
How does this regular expression work?
witnesstheday




msg:3829386
 8:58 am on Jan 19, 2009 (gmt 0)


s/^([^ ]+) +([^ ]+)/$2 $1/; # swap first two words

So i don't get, to begin with, the logic of the left side of the substitution... inside each of those brackets - what confuses me is the ^ - which I know, although only because I recently read it, that it's the same as \A, i.e. start of a string.

I want to know
(a) how the word characters are matched - i just see whitespace
(b) why the second item has a ^ as well - surely it's no longer "start of a string" by that point?

Help appreciated,

cheers,
Shams

 

phranque




msg:3829395
 9:35 am on Jan 19, 2009 (gmt 0)

to break it down, the [] indicates a character class.
within that context, if the caret (^) is the first character it means "not".
so [^ ] is a character class contain all characters that are not a blank.
as you probably know, the () is for a capturing group and the + means "one or more".

so between the first pair of forward slashes, you have captured in group 1 the leading one or more consecutive non blank characters in the string, followed by one or more blanks, followed by a capturing group 2 containing one or more consecutive non blank characters.

witnesstheday




msg:3829478
 1:11 pm on Jan 19, 2009 (gmt 0)

cheers that clears it up - it's the old caret I was clearly not understanding the right context of. Now I get it. Crystal clear. So possibly \S could have gone instead of [^ ] both times maybe? Yep. I tried it out and it worked. Nice.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved