Regex to allow some special characters c# - c#

I have to check whether a string contains special characters or not but I can allow these 5 special characters in it .()_-
i have written my regex as
var specialCharacterSet = "^[()_-.]";
var test = Regex.Match("a!", specialCharacterSet);
var isValid = test.Success;
but its throwing an:
error parsing "^[()_-.]" - [x-y] range in reverse order.

You have specified a range with -. Place it at the end:
[()_.-]
Otherwise the range is not correct: the lower boundary symbol _ appears later in the character table than the upper bound symbol .:
Also, if you plan to check if any of the character inside a string belongs to this set, you should remove ^ that checks only at the beginning of a string.
To test if a string meets some pattern, use Regex.IsMatch:
Indicates whether the regular expression finds a match in the input string.
var specialCharacterSet = "[()_.-]";
var test = Regex.IsMatch("a!", specialCharacterSet);
UPDATE
To accept any string value that doesnt contains the five characters, you can use
var str = "file.na*me";
if (!Regex.IsMatch(str, #"[()_.-]"))
Console.WriteLine(string.Format("{0}: Valid!", str));
else
Console.WriteLine(string.Format("{0}: Invalid!", str));
See IDEONE demo

You can use ^[()_\-.] or ^[()_.-] if you use special characters then best use \ before any special characters (which are used in regex special char.).

[()_.-]
Keep - at end or escape it to avoid it forming an invalid range.- inside a character class forms a range.Here
_ is decimal 95
. is decimal 46.
So it is forming an invalid range from 95 to 46

var specialCharacterSet = "^[()_.-]";
var test = Regex.IsMatch("a!", specialCharacterSet);
Console.WriteLine(test);
Console.ReadLine();

Convert all special characters in a pattern to text using Regex.Escape(). Suppose you already have using System.Text.RegularExpressions;
string pattern = Regex.Escape("[");
then check like this
if (Regex.IsMatch("ab[c", pattern)) Console.WriteLine("found");
Microsoft doesn't tell about escape in the tutorial. I learned it from Perl.

The best way in terms of C# is [()_\-\.], because . and - are reserved characters for regex. You need to use an escape character before these reserved characters.

Related

Validate string to have only one occurrence of `-` or `.` special characters inside it

I have a scenario where I need to validate given string which only be allowed to have - or . special characters in the middle of the given string.
It cannot have - or . special characters at the beginning or end of the string.
either - or . are allowed in a given string, not both of them at same time (at most one occurrence allowed).
I used Regex to validate given string.
Regex regex = new Regex(#"(^[a-zA-Z]+[.|-]?([a-zA-Z]+)$)");
and validating string passing into IsMatch method
regex.IsMatch(givenString)
Above is the solution I came up with. Is there a better way to validate this scenario?
Thanks
Your current regex does not allow a single char input while it is possible to have a. You may fix it using a grouping construct with a ? quantifier set to it:
var regex = new Regex(#"^[a-zA-Z]+(?:[.-][a-zA-Z]+)?$");
// or, using the case insensitive modifier
var regex = new Regex(#"^[A-Z]+(?:[.-][A-Z]+)?$", RegexOptions.IgnoreCase);
Details
^ - start of string
[a-zA-Z]+ - 1 or more ASCII letters
(?:[.-][a-zA-Z]+)? - one or zero repetitions of . or - followed with 1 or more ASCII letters
$ - end of string (or \z in case you do not want to allow a match before a trailing \n).
See the regex demo.

Regex pattern in c# start with # and end with 9;

Need regex pattern that text start with"#" and end with " ";
I tried the below pattern
string pattern = "^[#].*?[ ]$";
but not working
Since is an hex code of tab character, why not just using StartsWith and EndsWith methods instead?
if(yourString.StartsWith("#") && yourString.EndsWith("\\t"))
{
// Pass
}
This patterns works fine. I have tested it.
string pattern = "#(.*?)9";
See below link to test it online.
https://regex101.com/r/iR6nP6/1
C#
const string str = "dadasd#beetween9ddasdasd";
var match = Regex.Match(str, "#(.*?)9");
Console.WriteLine(match.Groups[1].Value);
In regex syntaxt, the [] denotes a group of characters of which the engine will attempt to match one of. Thus, [&#x9] means, match one of an &, #, x or 9 in no particular order.
If you are after order, which seems you are, you will need to remove the []. Something like so should work: string pattern = "^#.*?&#x9$";
you mean something like:
string pattern = "^#.*?[ ]$"
There are also many fine regex expression helpers on the web. for example https://regex101.com/ It gives a nice explanation of how your text will be handled.
You should use \t to match tab character
You can use special character sequences to put non-printable characters in your regular expression. Use \t to match a tab character (ASCII 0x09)
Try following Regex
^\#.*\t\;$

C# Regex Range in Reverse order

I have got list of ASCII Codes of character which are allowed in the name.So, I am trying to build regex patter using range(-) hypen operator and string length should be 40.
Finally, I have ended up by creating following pattern.
^([\x20-\x21\x23-\x25\x28-\x2E\x30-\x3B\x3F-\x7E\xA0-\xFF]){0,40}$
with this pattern I am specifying the range of character's ASCII codes allowed in the string.
But it throws exception of Range in reverse order. I have gone through couple of question. I have found that it happens because of hypen(-) character. So, In order to remove this problem I have to use escape sequence (-) instead of(-).
After adding escape sequence although it doesn't throw exception but it doesn't give the desire result.
So, I want to know is my pattern is correct or Is it right away to specify ASCII Code character range.
You need to use a negated character class, remove the grouping, quantifier, anchors and fix the typo:
[^\x20-\x21\x23-\x25\x28-\x2E\x30-\x3B\x3F-\x7E\xA0-\xFF]
See the regex demo (1 match is found before here) and use it as shown in the below C# demo:
var str = " some text here ";
if (str.Length > 40 || Regex.IsMatch(str, #"[^\x20-\x21\x23-\x25\x28-\x2E\x30-\x3B\x3F-\x7E\xA0-\xFF]"))
Console.WriteLine("The line is too long or contains invalid char(s)!");
Note that a negated character class is formed with the help of [^....] notation and matches all characters other than those specified in the character class.
If performance is key, you need to declare the regex as a static readonly field with RegexOptions.Compiled flag. Have a look at the Kurt Schindler's Regular expression performance comparisons blog.

Regex for my password validation

I need a regular expression for my password format. It must ensure that password only contains letters a-z, digits 0-9 and special characters: .##$%&.
I am using .NET C# programming language.
This is my code:
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]$");
if (!userAndPassPattern.IsMatch(username) || !userAndPassPattern.IsMatch(password))
return false;
The problem is that I always get back false.
!A || !B is logically equivalent to !(A && B)
So you could write better
!(userAndPassPattern.IsMatch(username) && userAndPassPattern.IsMatch(password))
Then you have a special character $ in you character class, maybe you need to mask it \$
I'm not quite sure about this, because in a character class it is not a special character. Maybe it depends on the RegEx engine in use. If you mask the $ it should do no harm ([a-z0-9.##\$%&])
Then you have just a single character to match. You need a quantifier
[a-z0-9.##$%&] means one single character out of the given, will match aor b or 0 but not ab
[a-z0-9.##$%&]+ many characters out of the given, from 1 to endless appearances, will match a, b, and ab and ba etc.
edit
This is what you want
Regex userAndPassPattern = new Regex("^[a-z0-9\.##\$%&]+$");
if (!(userAndPassPattern.IsMatch(username) && userAndPassPattern.IsMatch(password))) {
return false;
}
You forgot to add the '+' for matching one or more times:
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]+$");
This code Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]$"); will only match a username or password that is a single character long.
You are looking for something like this Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]+$"); which will match one or more of the characters in your class. The + symbol tells it to match one or more of the previous atom (which in this case is the character class you specified in the square brackets)
Also, if you did not mean to constrain the match to lowercase characters, you should add 'A-Z' to the character class Regex userAndPassPattern = new Regex("^[A-Za-z0-9.##$%&]$");
You might also want to implement a minimum length restriction which can be accomplished by replacing the + with the {n,} construct, where n is the minimum length you want to match. For example:
this would match a minimum of 6 characters
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]{6,}$");
this would match a minimum of 6 and a maximum of 12
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]{6,12}$");
You have two problems. First . and $ need to be escaped. Second you are matching only 1 character. Add a + before the last $:
^[a-z0-9\.##\$%&]+$
Edit: Another suggestion, if you have a minimum/maximum length you can replace the + with, for example, {6,16} or whatever you think is appropriate. This will match strings that are 6 to 16 character inclusive and reject any shorter or longer strings. If you don't care about an upper limit, you could use {6,}.
Have you tried using a verbatim string literal when you're using regex escape sequences?
Regex userAndPassPattern = new Regex(#"^[a-z0-9##\$%&]+$");
if (!userAndPassPattern.IsMatch(username) || !userAndPassPattern.IsMatch(password))
return false;
Your pattern only allows a single character set you probably want a repetition operator like * + or {10,}.
Your character set includes . which matches any character, defeating the object of the character class. If you wanted to match "." then you need to escape it with \.

How to check for special characters using regex

NET. I have created a regex validator to check for special characters means I donot want any special characters in username. The following is the code
Regex objAlphaPattern = new Regex(#"[a-zA-Z0-9_#.-]");
bool sts = objAlphaPattern.IsMatch(username);
If I provide username as $%^&asghf then the validator gives as invalid data format which is the result I want but If I provide a data s23_#.-^&()%^$# then my validator should block the data but my validator allows the data which is wrong
So how to not allow any special characters except a-z A-A 0-9 _ # .-
Thanks
Sunil Kumar Sahoo
There's a few things wrong with your expression. First you don't have the start string character ^ and end string character $ at the beginning and end of your expression meaning that it only has to find a match somewhere within your string.
Second, you're only looking for one character currently. To force a match of all the characters you'll need to use * Here's what it should be:
Regex objAlphaPattern = new Regex(#"^[a-zA-Z0-9_#.-]*$");
bool sts = objAlphaPattern.IsMatch(username);
Your pattern checks only if the given string contains any "non-special" character; it does not exclude the unwanted characters. You want to change two things; make it check that the whole string contains only allowed characters, and also make it check for more than one character:
^[a-zA-Z0-9_#.-]+$
Added ^ before the pattern to make it start matching at the beginning of the string. Also added +$ after, + to ensure that there is at least one character in the string, and $ to make sure that the string is matched to the end.
Change your regex to ^[a-zA-Z0-9_#.-]+$. Here ^ denotes the beginning of a string, $ is the end of the string.

Categories