mrblah
mrblah

Reputation: 103487

Regex for alphanumeric and the + character

I need a regex that allows only alphanumeric plus the + and - character.

Right now I am using:

[^\w-]

Upvotes: 3

Views: 5832

Answers (6)

Fredrik Mörk
Fredrik Mörk

Reputation: 158289

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

Upvotes: 10

Draemon
Draemon

Reputation: 34711

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]*$

Upvotes: 1

Blixt
Blixt

Reputation: 50169

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.
}

Upvotes: 4

David M
David M

Reputation: 72840

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

Upvotes: 1

instanceof me
instanceof me

Reputation: 39138

You have to escape the - char: [\w\-+] for single character and [\w\-+]+ for more.

Upvotes: 1

Canavar
Canavar

Reputation: 48088

Try this :

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

Upvotes: 1

Related Questions