ASP.NET regular expression to restrict consecutive characters - asp.net

Using ASP.NET syntax for the RegularExpressionValidator control, how do you specify restriction of two consecutive characters, say character 'x'?

You can provide a regex like the following:
(\\w)\\1+
(\\w) will match any word character, and \\1+ will match whatever character was matched with (\\w).
I do not have access to asp.net at the moment, but take this console app as an example:
Console.WriteLine(regex.IsMatch("hello") ? "Not valid" : "Valid"); // Hello contains to consecutive l:s, hence not valid
Console.WriteLine(regex.IsMatch("Bar") ? "Not valid" : "Valid"); // Bar does not contain any consecutive characters, so it's valid

Alexn is right, this is the way you match consecutive characters with a regex, i.e. (a)\1 matches aa.
However, I think this is a case of everything looking like a nail when you're holding a hammer. I would not use regex to validate this input. Rather, I suggest validating this in code (just looping through the string, comparing str[i] and str[i-1], checking for this condition).

This should work:
^((?<char>\w)(?!\k<char>))*$
It matches abc, but not abbc.
The key is to use so called "zero-width negative lookahead assertion" (syntax: (?! subexpression)).
Here we make sure that a group matched with (?<char>\w) is not followed by itself (expressed with (?!\k<char>)).
Note that \w can be replaced with any valid set of characters (\w does not match white-spaces characters).
You can also do it without named group (note that the referenced group has number 2):
^((\w)(?!\2))*$
And its important to start with ^ and end with $ to match the whole text.
If you want to only exclude text with consecutive x characters, you may use this
^((?<char>x)(?!\k<char>)|[^x\W])*$
or without backreferences
^(x(?!x)|[^x\W])*$
All syntax elements for .NET Framework Regular Expressions are explained here.

You can use a regex to validate what's wrong as well as what's right of course. The regex (.)\1 will match any two consecutive characters, so you can just reject any input that gives an IsValid result to that. If this is the only validation you need, I think this way is far easier than trying to come up with a regex to validate correct input instead.

Related

Extract mm/dd/yyyy and m/dd/yyyy dates from string in R [duplicate]

My regex pattern looks something like
<xxxx location="file path/level1/level2" xxxx some="xxx">
I am only interested in the part in quotes assigned to location. Shouldn't it be as easy as below without the greedy switch?
/.*location="(.*)".*/
Does not seem to work.
You need to make your regular expression lazy/non-greedy, because by default, "(.*)" will match all of "file path/level1/level2" xxx some="xxx".
Instead you can make your dot-star non-greedy, which will make it match as few characters as possible:
/location="(.*?)"/
Adding a ? on a quantifier (?, * or +) makes it non-greedy.
Note: this is only available in regex engines which implement the Perl 5 extensions (Java, Ruby, Python, etc) but not in "traditional" regex engines (including Awk, sed, grep without -P, etc.).
location="(.*)" will match from the " after location= until the " after some="xxx unless you make it non-greedy.
So you either need .*? (i.e. make it non-greedy by adding ?) or better replace .* with [^"]*.
[^"] Matches any character except for a " <quotation-mark>
More generic: [^abc] - Matches any character except for an a, b or c
How about
.*location="([^"]*)".*
This avoids the unlimited search with .* and will match exactly to the first quote.
Use non-greedy matching, if your engine supports it. Add the ? inside the capture.
/location="(.*?)"/
Use of Lazy quantifiers ? with no global flag is the answer.
Eg,
If you had global flag /g then, it would have matched all the lowest length matches as below.
Here's another way.
Here's the one you want. This is lazy [\s\S]*?
The first item:
[\s\S]*?(?:location="[^"]*")[\s\S]* Replace with: $1
Explaination: https://regex101.com/r/ZcqcUm/2
For completeness, this gets the last one. This is greedy [\s\S]*
The last item:[\s\S]*(?:location="([^"]*)")[\s\S]*
Replace with: $1
Explaination: https://regex101.com/r/LXSPDp/3
There's only 1 difference between these two regular expressions and that is the ?
The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?, .+? etc) are a Perl 5 extension which isn't supported in traditional regular expressions.
If your stopping condition is a single character, the solution is easy; instead of
a(.*?)b
you can match
a[^ab]*b
i.e specify a character class which excludes the starting and ending delimiiters.
In the more general case, you can painstakingly construct an expression like
start(|[^e]|e(|[^n]|n(|[^d])))end
to capture a match between start and the first occurrence of end. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e only if it isn't followed by nd and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.
Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.
Because you are using quantified subpattern and as descried in Perl Doc,
By default, a quantified subpattern is "greedy", that is, it will
match as many times as possible (given a particular starting location)
while still allowing the rest of the pattern to match. If you want it
to match the minimum number of times possible, follow the quantifier
with a "?" . Note that the meanings don't change, just the
"greediness":
*? //Match 0 or more times, not greedily (minimum matches)
+? //Match 1 or more times, not greedily
Thus, to allow your quantified pattern to make minimum match, follow it by ? :
/location="(.*?)"/
import regex
text = 'ask her to call Mary back when she comes back'
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
print (match.group(1))
Output:
Mary

RegularExpression Validator For Textbox

In my requirement a Textbox should allow Alphabets,Numeric s, Special Characters,Special Symbols With at least one Alphabet.
I will try like this but i am not getting.
^\d*[a-zA-Z][a-zA-Z0-9#*,$._&% -!><^#]*$
You may want to have 2 regular expression validators; one for validating the allowed characters, and one for validating that at least on alphabet has been provided. You may be able to get at least one, but this way, you can have two separate validation messages to show the user explaining why the input is wrong.
Just match for special characters until you encounter a letter, then match for everything until the end of the string:
^[0-9#*,$._&% -!><^#]*[a-zA-Z0-9#*,$._&% -!><^#]*$
Use lookaheads :
/^(?=.*[a-zA-Z])[\w#*,$.&%!><^#-]*$/
Edit :
I assume the - is meant as the actual - character and not a range of space to !.
I removed the space character. You can of course add it if you want.
[ -!]
Effectively means :
[ -!] # Match a single character in the range between “ ” and “!”
And I have no idea what that range entails!

Problem with an asp net password regular expression?

I'm trying to validate the following in a password field:
-at least 1 alpha
-at least 1 numeric
-at least 1 special (non alphanumeric)
My reg exp is this:
Regex.IsMatch("jpere33z#1?hs", #"^\w*(?=\w*\d)(?=\w*[a-z])(?=\W*)\w*$")
and it says it is not valid. The \W part is what is not working.
Could you please tell me why?
\w*$ will only match letters, numbers, and underscore. This is what you want:
Regex.IsMatch("#1?hsjpere33z", #"^(?=.*?\d)(?=.*?[a-z])(?=.*?\W).*$", RegexOptions.IgnoreCase)
I moved the validation to the left, and added \w* right before the \W.
Edit: Also used .* instead of \w for test lookaheads.
Your regex doesn't allow more then 1 digit.
Your easiest route would probably be to have 3 regex checks, one for the existance of each character type.
This is difficult to do with regex (at least only one). In the regex you are giving the fields an order, so the parser expects them in that order.
One alternative would be to use a choice, but that would make difficult to check that you have one of each of the terms:
[\w|\d|\W]{4,}
If you want to use regex, check three of them:
1) Is there a digit?
2) Is there a character?
3) Is there a special?
If all of them are true.... bingo!

Regular Expression Password Validator

I'm having a hard time trying to create a right regular expression for the RegularExpressionValidator control that allows password to be checked for the following:
- Is greater than seven characters.
- Contains at least one digit.
- Contains at least one special (non-alphanumeric) character.
Cant seem to find any results out there too. Any help would be appreciated! Thanks!
Maybe you will find this article helpful. You may try the following expression
^.*(?=.{8,})(?=.*[\d])(?=.*[\W]).*$
and the breakdown:
(?=.{8,}) - contains at least 8 characters
(?=.*[\d]) - contains at least one digit
(?=.*[\W]) - contains at least one special character
http://msdn.microsoft.com/en-us/library/ms972966.aspx
Search for "Lookaround processing" which is necessary in these examples. You can also test for a range of values by using .{4,8} as in Microsoft's example:
^(?=.*\d).{4,8}$
Try this
((?=.*\d)(?=.*[a-z])(?=.*[\W]).{6,20})
Description of above Regular Expression:
( # Start of group
(?=.*\d) # must contains one digit from 0-9
(?=.*[a-z]) # must contains one lowercase characters
(?=.*[\W]) # must contains at least one special character
. # match anything with previous condition checking
{7,20} # length at least 7 characters and maximum of 20
) # End of group
"/W" will increase the range of characters that can be used for password and pit can be more safe.
Use for Strong password with Uppercase, Lowercase, Numbers, Symbols & At least 8 Characters.
//Code for Validation with regular expression in ASP.Net core.
[RegularExpression(#"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$")]
Regular expression password validation:
#"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$"

Regex to test if an input string contains a certain number of characters

So, I basically would like to test to see if a string contains a range of alphanumeric characters. It's to be used as a client-side validation and I don't want to prevent users from entering whatever they want. Best to give examples of what should/should not pass validation:
So to be specific, the expression I'm looking for is to test to make sure string contains anywhere from 3 to 10 alphanumeric characters. I'd like to plug into an ASP.NET client side validator.
NOTE: quotes not part of input (but could be!)
" f o o " should pass since there are 3 chars
"f_0_0" should pass
" fo " should not
"F......o......o......b.....a......r" should pass
thx
^([^a-zA-Z0-9]*[a-zA-Z0-9][^a-zA-Z0-9]*){3,10}$
Allows for exactly 3-10 alphanumeric characters, each surrounded by an arbitrary number of non-alphanumeric characters.
(Untested, but it should conform to the JScript subset of the standard .net Regex syntax, as required by the RegularExpressionValidator. Unfortunately, the shorthands \w and \W cannot be used since they include the underscore as an alphanumeric character.)
I'm not familiar with ASP.NET client-side validators, so I'm not sure if you need to do this in a regex, but potentially an easy solution is as follows:
Remove all non-alphanumeric characters (regex replace [^0-9A-Za-z] with nothing).
Check if string length is 3 or greater.

Resources