I want to do some basic String testing in Node.js. Assume I have a form where users enter their name and I wanna check if it's just rubbish or a real name.
Happily (or sadly for my check) I get users from all around the world which means that their names contain non-english characters, like ä ö ü ß é
. I was used to use /[A-Za-z -]{2,}/
but this doesn't match names like "Jan Buschtöns"
.
Do I have to manually add every possible non-english but latin character to my RegEx to work? I don't want a 100+ characters long RegEx like /[A-Za-z -äöüÄÖÜßéÉèÈêÊ...]{2,}/
.
Check http://www.regular-expressions.info/unicode.html and http://xregexp.com/plugins/
You would need to use \p{L}
to match any letter character if you want to include unicode.
Speaking unicode, alternative of \w
is [\p{L}\p{N}_]
then.
The answer depends on exactly what you want to do.
As you have noticed, [A-Za-z]
only matches Latin letters without diacritics.
If you only care about German diacritics and the ß ligature, then you can just replace that part with [A-Za-zÄÖÜäöüß]
, e.g.:
/[A-Za-zÄÖÜäöüß -]{2,}/
But that probably isn’t what you want to do. You probably want to match Latin letters with any diacritics, not just those used in German. Or perhaps you want to match any letters from any alphabet, not just Latin.
Other regular expressions dialects have character classes to help you with problems like this, but unfortunately JavaScript’s regular expression dialect has very few character classes and none of them help you here.
(In case you don’t know, a “character class” is an expression that matches any character that is a member of a predefined group of characters. For example, \w
is a character class that matches any ASCII letter, or digit, or an underscore, and .
is a character class that matches any character.)
This means that you have to list out every range of UTF-16 code units that corresponds to a character that you want to match.
A quick and dirty solution might be to say [a-zA-Z\u0080-\uFFFF]
, or in full:
/[A-Za-z\\u0080-\\uFFFF -]{2,}/
This will match any letter in the ASCII range, but will also match any character at all that is outside the ASCII range. This includes all possible alphabetic characters with or without diacritics in any script. However, it also includes a lot of characters that are not letters. Non-letters in the ASCII range are excluded, but non-letters outside the ASCII range are included.
The above might be good enough for your purposes, but if it isn’t then you will have to figure out which character ranges you need and specify those explicitly.