Dave's Brain

Browse - Programming Tips - How can I extract the first word in a string?

Date: 2017jun15
Language: Perl

Q.  How can I extract the first word in a string?

A.

sub extractFirstWord($) { my($s) = @_; if ($s !~ m/^(\w+)/) { return '' } return $1; }
We use the not-match operator !~ If the regex of \w+ doesn't match we return '' Otherwise the first word is in $1

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.