Combine 2 or more regex in 1 - c#

I've 2 regular expression:
string regex1 = "(?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$)"; this will check for 'admin' substring in the given string and case is insensitive.
string regex2 = "^[^<>?]{5,100}$"; this will check for special char(^<>?) and length between 5 to 100 only.
I want a regular expression where both the regex can be validated at once with the use of only single regex.
Ex-
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtBox1" ErrorMessage="Validation Failed!"
ValidationExpression="(?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$)">
</asp:RegularExpressionValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="txtBox2" ErrorMessage="Length Validation Failed!"
ValidationExpression="^[^<>?]{5,100}$">
</asp:RegularExpressionValidator>
Q. Can we have a single "RegularExpressionValidator" that serves both the above functionality?

The (?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$) regex is too redundant, it is equal to (?i)^(?!^.*?admin).*$. It basically matches any string that contains no admin substring.
The ^[^<>?]{5,100}$ regex disallows <, > and ? in the string and sets string length limit.
Combining the two is done by replacing the .* in the first pattern with the consuming part of the second regex ([^<>?]{5,100}):
(?i)^(?!^.*?admin)[^<>?]{5,100}$
Details
(?i) - case insensitive mode on
^ - start of string
(?!^.*?admin) - no admin substring allowed anywhere after 0 or more chars other than line break chars, as few as possible
[^<>?]{5,100} - five to a hundred chars other than <, > and ?
$ - end of string.

Related

Regex to find invalid characters in integer with whitespaces

I want to use regular expression (regex) to find invalid characters in a string. The string is a user input and when the regex finds invalid characters I want to give the user feedback which characters where invalid. Example warning message: "Only 0-9 and whitespace allowed. Found invalid characters: ab" when input was "- 10 a 0 b".
A valid string is:
integer
negative or positive
is allowed to have any amount of whitespace at any position.
So for example those VALID strings should NOT match the regex:
"-100"
"- 1 00"
" - 1 00"
"100"
" 1 0 0 "
"1 00"
While the regex should find matches in these INVALID strings:
"- 1 a 0 0 b" should match "a" and "b"
"- 1 a 0 0 -" should match "a" and "-"
I had a working regex for positive integers, until i found out that I forgot to include negative integers:
var regex = new Regex(#"[^0-9\s]")
var invalidCharacters = regex.Matches(text)
I have only very basic knowledge of regex. I tried out negating the regex to include negative integers, but it is not working:
new Regex(#"(?!-?[0-9\s])")
I hope someone can help me with this. If this can be solved easier by removing the whitespace requirement. Then please feel free to ignore the whitespace part.
I would approach this by thinking about the positive case first - which strings are valid? And then negate that with a negative lookaround.
I think this meets your requirements:
(?!\s*-?[\d\s]).
\s* will match any whitespace at the start
-? will optionally match a hyphen
[\d\s] will match numbers and whitespace
(?!expression) is a negative lookaround to negate the whole expression
The . at the end is a way to generate matches. The negative lookaround is just an assertion - it doesn't return any results.
It produces the desired results for the test cases in your question.
You may use
var invalidCharacters = Regex.Matches(text, #"[^0-9\s-]|(?<!^\s*)-");
See the regex demo (modified a bit as the demo is a test against a single multiline string.)
The regex matches:
[^0-9\s-] - a char other than an ASCII digit, any Unicode whitespace char or a - char
| - or
(?<!^\s*)- - a - char that is not preceded with the start of string any any 0+ whitespace chars.

Regular expressions to match these pdf file names

I am looking for a regular expression to match the fileNamePattern.
Files are pdf can have these names: 8 alphanumeric chars, -, 4 alphanumeric chars, -, 4 alphanumeric chars, -, 4 alphanumeric chars, -, 12 alphanumeric chars + .pdf.
Examples:
5b7f991f-0726-4dd5-856e-7cea820f02c5.pdf
138bcee6-db7f-47a7-97bf-69c0b3989698.pdf
e988315b-ade7-48e5-9733-35bb59a3c28d.pdf
I am using
^[A-Z][0-9]{8}[-][A-Z][0-9]{4}[-][A-Z][0-9]{4}[-][A-Z][0-9]{4}[-][A-Z][0-9]{12}[.]pdf
However, I am not sure it is correct as I get no matches.
Regex r = new Regex(#"^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\.pdf$");
If you explicitly don't want underscores, you can use:
^[a-zA-Z\d]{8}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{12}\.pdf$
Regex is case-sensitive (unless you specify it to ignore case using RegexOptions.
Right now the main issue is that your regex is saying to match a letter then match n digits instead of matching n alphanumeric characters.
With setting the case insensitive flag, your regex can simplify to:
^[A-Z\d]{8}-[A-Z\d]{4}-[A-Z\d]{4}-[A-Z\d]{4}-[A-Z\d]{12}\.pdf$
You only match uppercase letters in your regex, and when you use [A-Z][0-9]{4} you do not match four alphanumeric chars, you match a letter followed with 4 digits.
So, you need to merge [A-Z][0-9] into single character classes [A-Z0-9] and then use a case insensitive flag.
Also, you need to use $ at the end of the regex to make the pattern match the entire string.
Use
^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$
See the regex demo
In C#,
var rx = new Regex(#"^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$", RegexOptions.IgnoreCase);
Note that case insensitivity can be set with an inline modifier (?i):
var pattern = #"(?i)^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$";
// check if the string matches the pattern
if (Regex.IsMatch(s, pattern)
{
// The string matches...
}
This should work
/(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})(.pdf)/i
I tried it at here at RegEx Testing
\w = alphanmumeric
{n} = times the sign should appear
gi = are flags: "i" = case insensitive.

asp validation for multiple spaces between strings

I've a textbox for name field where I've used asp validation for proper name format. I want to validate multiple spaces between the strings. How can I do that? The leading and trail spaces are removed by trim() function but how can I validate multiple spaces between the strings? like
multiple spaces
no space
My validation code::
<label>
<span>Full name</span>
<input type="text" id="txt_name" runat="server" required="required"/>
<asp:RegularExpressionValidator ID="rev_txt_name" runat="server" ControlToValidate="txt_name" ForeColor="Red"
ErrorMessage="Invalid name!" SetFocusOnError="True" ValidationExpression="^[a-zA-Z'.\s]{2,50}"></asp:RegularExpressionValidator>
</label>
The pattern you are using allows matching whitespace anywhere inside the string and any occurrences, consecutive or not, since it is part of a rather generic character class. You need to use a grouping and quantify it accordingly:
^(?=.{2,50}$)[a-zA-Z'.]+(?:\s[a-zA-Z'.]+)*$
Note that the (?=.{2,50}$) lookahead requires the whole line to be of 2 to 50 chars long.
See the regex demo.
Details:
^ - start of string
(?=.{2,50}$) - a positive lookahead requiring any 2 to 50 chars other than a newline up to the end of the string
[a-zA-Z'.]+ - 1+ letters, single quote or dot chars
(?: - a non-capturing group start:
\s - 1 whitespace
[a-zA-Z'.]+ - 1+ letters, single quote or dot chars
)* - zero or more (*) occurrences
$ - end of string

Can't detect '#' as special key (Regex Asp.net)

I'm new on Asp. I have a problem to using regex for checking password input. Here the regex
<asp:RegularExpressionValidator ID="Regex1" runat="server"
ErrorMessage="Password must contain: Minimum 8 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet, 1 Number and 1 Special Character"
Font-Italic="True" Font-Size="Small" ForeColor="Red"
ValidationExpression="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,}"
ControlToValidate="TextBoxNewPassword" Display="Dynamic" />
When I input "Hamlida123#" regex did'nt allow it. How to solve this?
You need to include the '#` character specifically in the regex, like so:
ValidationExpression="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&#])[A-Za-z\d$#$!%*?&#]{8,}"
Demo
Based on your current regex, I assume that you are only allowing certain non-word characters, and so you would need to list every allowable character in your regex as shown above.

Conditional Validation on a text field

I have a text field and I want to have a validation which verify if it starts with 0 the length will be 10, else will be 13.
I want to know if I can write in validation expression like "^0..." not in function.
I hope you can help me.
I code in ASP.NET, C#.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Text="dsg" ErrorMessage="RegularExpressionValidator" ValidationExpression="[^0]{0-10},[^1]{0-13}" ControlToValidate="TextBox1"></asp:RegularExpressionValidator>
This doesn't work , but I want something like this.
Your regex [^0]{0-10},[^1]{0-13} means:
[^0] - Match anything but 0 (even a comma)
{0-10}, - Match literal string {0-10}, (because of the hyphen inside {...})
[^1] - Match anything but 1
{0-13} - Match literal {0-13} string.
If you plan to use only server-side validation, you can use .NET regex to validate
if it starts with 0 the length will be 10 , else will be 13.
:
^(0)?(?(1)\d{9}|\d{13})$
See demo
In case you also plan to use it on the client side, you will need a JavaScript regex flavor where you cannot use conditionals:
^(?:0\d{9}|\d{13})$
See another demo
[^0]{0-10} means from 0 up to 10 characters not equal to 0. The ^ does not have the same meaning in the beginning of the regular expression and later.
A regular expression for a string of 10 characters starting with 0 is ^0.{9}$.
The other is ^[^0].{12}$.
So together: ^(0.{9}|[^0].{12})$

Categories

Resources