Synopsis Count words in a line.
Examples A slighly more involved manner of using regular matching in a loop.
module demo::common::WordCount::CountInLine2

public int countInLine2(str S){
  int count = 0;
  // \w matches any word character
  // \W matches any non-word character
  // <...> are groups and should appear at the top level.
  while (/^\W*<word:\w+><rest:.*$>/ := S) { 
    count += 1; 
    S = rest; 
  return count;
The pattern /^\W*<word:\w+><rest:.*$>/ can be understood as follows:
  • The ^ makes it anchored, only matches at the begin of the substring S.
  • \W* matches zero or more non-word characters.
  • <word:\w+> matches one or more word characters and assigns the result to the variable word.
  • <rest:.*$> matches the remaining part of S.
Inside the loop count is incremented and the new value of S becomes the remainder of the current match. To summarize: each iteration removes the first word from S and counts it.

Here is `countInLine2 in action:
rascal>import demo::common::WordCount::CountInLine2;
rascal>countInLine2("Jabberwocky by Lewis Carroll");
int: 4
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit