Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Except this Characters

Tags:

c#

regex

I am using MVC data annotations and my requirement is that the address field can contain any characters (i.e. other than English characters are also allowed) except < > . ! @ # % / ? *.

I searched many sites but not getting how to write this regex.

So far I have tried:

[Required(ErrorMessage = "Address Required.")]
[RegularExpression(@"^[<>.!@#%/]+$", ErrorMessage = "Address invalid.")]
public string Address { get; set; }
like image 595
d.Siva Avatar asked Sep 14 '12 10:09

d.Siva


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

Which regular expression matches any character except XYZ?

Wildcard which matches any character, except newline (\n). Used to match 0 or more of the previous (e.g. xy*z could correspond to "xz", "xyz", "xyyz", etc.) ?!= or ?

What is the regular expression for characters?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.


4 Answers

Make your regex choose from any characters except the ones listed with the caret:

[^abc] 

will match anything that's not an a, b, or c.

So putting it all together, your regex would be

^[^<>!@#%/?*]+$

Note here that the caret outside the square braces means 'match the start of the line', yet inside the square brackets means 'match anything that is not any of the following'

like image 64
agentgonzo Avatar answered Oct 05 '22 08:10

agentgonzo


Try is regular expression:

[^<>.!@#%/?*]
like image 41
Aziz Shaikh Avatar answered Oct 05 '22 08:10

Aziz Shaikh


Currently, you are only allowing string consisting ONLY of these letters.

Use

"^[^<>.!@#%/]+$"
like image 36
Jens Avatar answered Oct 05 '22 07:10

Jens


This should do the work:

"[^<>.!@#%/]"

EDIT:

. (dot) is a reserved character in Regular Expressions, so you need to escape it.

like image 23
Alessandro Avatar answered Oct 05 '22 06:10

Alessandro