Hi,
I need a regex that allows only alphanumeric plus the + and - character.
Right now I am using:
[^\w-]
Hi,
I need a regex that allows only alphanumeric plus the + and - character.
Right now I am using:
[^\w-]
You have to escape the - char: [\w\-+]
for single character and [\w\-+]+
for more.
This regular expression will match only if you test it against a string that has alphanumeric characters and/or +
/-
:
^[a-zA-Z0-9\-+]+$
To use it:
if (Regex.IsMatch(input, @"^[a-zA-Z0-9\-+]+$"))
{
// String only contains the characters you want.
}
Matches single -, + or alpha-numeric:
[-+a-zA-Z0-9]
Matches any number of -, + or alpha-numeric:
[-+a-zA-Z0-9]*
Matches a string/line of just -, + or alpha-numeric:
^[-+a-zA-Z0-9]*$
The following pattern will match strings that contain only letters, digits, '+' or '-', including international characters such as 'å' or 'ö' (and excluding the '_' character that 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