Regex is a really powerful tool, but sometimes I wonder just how well people actually understand it as the vast majority of people (myself included) seem to be self taught in the syntax - only learning the bits they need as and when they need it.
The problem is, regular expressions is packed full of counter intuitive idiosyncrasies which make perfect sense once they're explained, but are far from obvious. Take this for example:
s/(^\s+|\s+$)//g
is slower than running two separate regex, like so:
s/^\s+//;
s/\s+$//;
So it does make me wonder the number of bugs that have been introduced to software by bad regex.
That wouldn't work. First, it will only grab at only one whitespace character at the beginning and at the end. Second, if there was whitespace at the beginning or the end but not both, it won't match at all. "^\s* (.* ?)\s* $/$1/g" would work.
Comments
Regex is a really powerful tool, but sometimes I wonder just how well people actually understand it as the vast majority of people (myself included) seem to be self taught in the syntax - only learning the bits they need as and when they need it.
The problem is, regular expressions is packed full of counter intuitive idiosyncrasies which make perfect sense once they're explained, but are far from obvious. Take this for example:
is slower than running two separate regex, like so: So it does make me wonder the number of bugs that have been introduced to software by bad regex.The speed difference is bigger than I would have expected - about one order of magnitude in perl with a simple test script : http://ideone.com/Yso23W
Use the s/, Luke
That wouldn't work. First, it will only grab at only one whitespace character at the beginning and at the end. Second, if there was whitespace at the beginning or the end but not both, it won't match at all. "^\s* (.* ?)\s* $/$1/g" would work.
point being: get rid of the anchors in the alternation.