View Full Version : Some help needed with easy regex

07-20-2009, 05:48 PM
Hi I'm trying to drill a lot of perl into my head having spent years programming it, currently going through my copy of the Blue Camel book reading up key chapters.

All going rather well except so far this bit of regex is really perplexing me:

([^ ]+)

what does it mean?

because here it is used to represent a word...

s/^([^ ]+) +([^ ]+)/$2 $1/;

which I do know, from the explanation, swaps words one and two around

but what is screwing me is this...

[^ ]+

what does it mean?

any number of whitespace characters in succession or the start of a string in succession? I'm a bit confused

I would have expected a \w in there somewhere, so that's why I want to know how it actually works...


07-20-2009, 06:01 PM
I've played around and come to the conclusion that in...

[^ ]

the stuff inside the sqare brackets means "not whitespace" (ie a synonym of \W)

and that ^ inside []s is a sort of "inversion operator"

that seems to be the case based on a wide variety of queries using ^ inside ['s
whereas outside []s a ^ seems to only mean the start of a string

is that correct Shannon? Boy I love learning perl. What a freako I am.

07-20-2009, 06:58 PM
That's correct. What you have is called a negated character class. It means to not match what is inside the character class, in this case white space. But it will match everything else that is not inside the character class, so any non-white space will be matched.

You will find some explanations and examples here as well as in your book:


Philip M
07-20-2009, 08:28 PM
([^ ]+) means match one or more characters which are not a space

([^\W]+ means match one or more characters which are not a-zA-Z0-9_
which is not exactly the same thing.

^ within square brackets means "not". Otherwise ^ means start of the string, and $ means the end of the string.

/^(Philip)/ matches Philip at the start of the string

[^xyz] matches anything which is not an x, a y or a z.

To swap two words in a string such as firstname lastname (Javascript):-

<script type = "text/javascript">

str = "John O'Smith-Jones"
str = str.replace(/^(\S+)\s+(\S+)$/,"$2 $1");
alert (str);


I expect Perl is the same.

07-20-2009, 11:51 PM
Wow. I did not expect to learn such cool javascript. And I thought it was just for goddamn mouseovers.