|
| |
| Navigation |
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:
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; ok rascal>countInLine2("Jabberwocky by Lewis Carroll"); int: 4 |