Regular expression for alphanumeric characters and +

I need a regular expression that only allows alphanumeric characters plus + and -.

Now I am using:

[^\w-]
+3
source share
6 answers

The following pattern will match strings that contain only letters, numbers, "+" or "-", including international characters such as "å" or "ö" (and excluding the "_" character, which is included in " \w'):

^[-+\p{L}\p{N}]+$

Examples:

string pattern = @"^[-+\p{L}\p{N}]+$";
Regex.IsMatch("abc", pattern); // returns true
Regex.IsMatch("abc123", pattern); // returns true
Regex.IsMatch("abc123+-", pattern); // returns true
Regex.IsMatch("abc123+-åäö", pattern); // returns true
Regex.IsMatch("abc123_", pattern); // returns false
Regex.IsMatch("abc123+-?", pattern); // returns false
Regex.IsMatch("abc123+-|", pattern); // returns false
+8
source

This regular expression will only match if you check it against a string with alphanumeric characters and / or +/ -:

^[a-zA-Z0-9\-+]+$

:

if (Regex.IsMatch(input, @"^[a-zA-Z0-9\-+]+$"))
{
    // String only contains the characters you want.
}
+4

:

[a-zA-Z0-9+\-]
+1

You need to avoid - char: [\w\-+]for a single character and [\w\-+]+for more.

+1
source

Matches one -, +, or alphanumeric:

[-+a-zA-Z0-9]

Matches any number -, +, or alphanumeric:

[-+a-zA-Z0-9]*

Matches a line / line only -, + or alphanumeric:

^[-+a-zA-Z0-9]*$
+1
source

[A-Za-Z0-9 \ + \ -]

0
source

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


All Articles