The following will match a string with a maximum of three different non-spatial characters
^\s*(\S)?(?:\s|\1)*(\S)?(?:\s|\1|\2)*(\S)?(?:\s|\1|\2|\3)*$
(\S) matches one non-spatial character and commits it so that it can then be referenced later in the regular expression using a backlink, for example. \1 . ? in (\S)? are used, so a string can contain zero, one, two, or three types of non-spatial characters.
?: makes the group not exciting.
The first part of the regular expression captures up to three different non-spatial characters \1 , \2 , \3 , and then (?:\s|\1|\2|\3)* ensures that only those characters or space \s can appear before end of line $ .
One way, in Javascript, is to count the number of different non-spatial characters in a line using regex:
var str = 'ABC ABC'; var chars = ''; str.replace( /\S/g, function ( m ) { if ( chars.indexOf(m) == -1 ) chars += m; }); chars.length;
Mikem source share