Nuno Cabrinha
Nuno Cabrinha

Reputation: 21

Javascript advanced regex count

I need to count characters in a string according to 3 different groups. I need a separate count for each, so 3 variables, but I can't seem to get the regex right, mostly because I'm never sure what to escape or not.

So type 1 would be:

[a-zA-Z0-9@¡¿£_!$"¥#è¤é%ù&ìYò(Ç)*:Ø+;øÆ,<æ-=ß.>É/?ÄäÖöÑñÜü§à]

as well as space, line feed and carriage return (it should count once for each)

Type 2 would be:

|^{}[]~\€

And type 3 would be anything not in the other 2 groups.

How would I go about setting up the regex match for each var?

EDIT: I have managed to get type 1 working, which was the easy one, but I can't seem to get type 2 to count those characters. I tried:

var type1 = ($(this).val().match(/[a-zA-Z0-9@¡¿£_!$"¥#è¤é%ù&ìYò(Ç)*:Ø+;øÆ,<æ\-=ß.>É/?ÄäÖöÑñÜü§à/\n/\r/\s]/g)||[]).length;
var type2 = ($(this).val().match(/[|{}[/]~^\\€]/g)||[]).length;
var type3 = $(this).val().length - type1 - type2;

Upvotes: 1

Views: 68

Answers (1)

Nuno Cabrinha
Nuno Cabrinha

Reputation: 21

After some trial and error, I have managed to get it working, apparently:

var type1 = ($(this).val().match(/[a-zA-Z0-9@@¡¿£_!$"¥#è¤é%ù&ìYò(Ç)*:Ø+;øÆ,<æ\-=ß.>É/?ÄäÖöÑñÜü§à/\n/\r/\s]/g)||[]).length;
var type2 = ($(this).val().match(/[|{}[\]~^\\€]/g)||[]).length;
var type3 = $(this).val().length - type1 - type2;

Upvotes: 1

Related Questions