s = "1 2 ";
StringCases[s, (n : NumberString ~~ " ") .. ]
StringCases[s, (NumberString ~~ " ") .. ]
yields
{"1 ", "2 "}
{"1 2 "}
Why?
Answer
Patterns get confusing quickly. If you name a pattern you're imposing more restrictions on that pattern that are sometimes difficult to follow. Using your example,
s = "1 2 ";
StringCases[s, (n : NumberString ~~ " ") .. ]
StringCases[s, (NumberString ~~ " ") .. ]
In the first case you're telling string cases to match n
, where n must be a number string and to continue the pattern for any match with the parenthetical statement repeated. In the repeated suffix n must always be the same number!
In the second case you're specifying that any repeated pattern of NumberString+Whitespace should match. Since you haven't named the number string, the pattern still applies generally to any number.
Trying
s = "1 1 1 2 2";
StringCases[s, (n : NumberString ~~ " ") .. ]
StringCases[s, (NumberString ~~ " ") .. ]
Will give:
{1 1 1 , 2 2 }
{1 1 1 2 2 }
Which shows that the first pattern works any time the integer following the white space is the same as the n that triggered the match.
Comments
Post a Comment