How to check the number of different characters with regular expressions?

I am trying to create a regex to find all inputs containing a maximum of three different characters. It doesn't matter how long the entry takes.

Case Study:

  • "32 32 32 32 34 34" β†’ match
  • "MM" β†’ match
  • "" β†’ match
  • "1234" β†’ no match

I did a regex to find input from four or more different characters, but now I need it the other way around ...

(.).*(?\1)(.).*(?\1)(?\2)(.).*(?\1)(?\2)(?\3)(.) 

The main question: how to check the number of different characters?

+6
source share
2 answers

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; // 3 
+3
source

Good q. Here is the simplest:

 ^\s*([^\s]{1,3}\s+)*[^\s]{0,3}$ 

Explanation:

  • ^\s* matches any number of spaces at the beginning.
  • ([^\s]{1,3}\s+)* matches repeating groups of one to three non-whitespace characters, followed by at least one space character. Put ?: After ( to make this group not exciting.
  • The final [^\s]{0,3} allows you to end the line with up to three characters without spaces (so that it should not end with a space, as provided for 2).

Visualization:

Regular expression visualization

Demo:

Test it here: Debuggex Demo

0
source

Source: https://habr.com/ru/post/943955/


All Articles