Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

How does this regular expression work?



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

5+ Year Member

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,



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

WebmasterWorld Administrator phranque is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

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.


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

5+ Year Member

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.

Featured Threads

Hot Threads This Week

Hot Threads This Month