Category: >> Perl Code >> Count all words in a string Bookmark and Share

<< lastnext >>

Snippet Name: Count all words in a string

Description: This search pattern will match what is generally considered to be a "word". We consider that we have found a word each time a white-space character (specified in regex as s) followed by a non-white-space character (specified in regex as S) is matched. The very first word in a string will usually not match this pattern since it usually isn't preceded by a white-space character. To handle this special case we add an extra variation to the pattern. The carat ^ will match the beginning of the string that is searched.

Also see:
» Transfer or migrate messages betwe...
» Active Directory - Reading the Use...
» Countdown to Enable a Download Link
» Create an array from words in an H...
» Count specific characters in a str...
» Regexp: Find and highlight repeate...
» Convert Dollars And Cents Value to...
» Reserved Words In Javascript
» Count Uppercase Letters In A String
» Pre-populated List of Countries
» Neatly trim a string to a set numb...
» Count capital letters in a string
» Search All Words Of A String In my...
» USER lock account
» USERS: Lock and Unlock accounts
» Count words or terms
» Count rows in all tables
» Spell out numbers to words
» Number Functions: COUNT
» Number Functions: COUNT (running c...
» Flat file counter
» Counting rows
» Random Pronounceable Passwords
» Highlight Words #2
» Count Textbox Chars
» Count checkboxes
» Capitalize first letter of words
» Auto-Link words

Comment: (none)

Author: CoderZone
Language: PERL
Highlight Mode: PERL
Last Modified: December 03rd, 2010

$str = "Be careful what you wish for—you just might get it.";
$count = $str =~ s/((^|\s)\S)/$1/g;
print $count;
# prints '11'
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© | users online: 9