I'm trying to write a regular expression for a username that fits the following criteria...
Must be between 6 and 16 characters,
any 4 of which must be letters (though not necessarily consecutive),
May also contain letters, numbers, dash and underscore.
So _1Bobby1_ and -Bo-By19- would match, but _-bo-_ and -123-456_ wouldn't.
I've tried:
^(?=.*[a-zA-Z].{4})([a-zA-Z0-9_-]{6,16})$
But this doesn't seem to work, I've looked online and can't find anything that works and used Regexper to visualise the expression and try to build it from scratch.
Any pointers would be greatly appreciated.
This regex can be used to verify username
^(?=.{6,16}$)(?=(?:.*[A-Za-z]){4})[\w-]+$
Regex Breakdown
^ #Start of string
(?=.{6,16}$) #There should be between 6 to 16 characters
(?=
(?:.*[A-Za-z]){4} # Lookahead to match 4 letter anywhere in string
)
[\w-]+ #If above conditions are correct, match the string. It should only contain dgits, alphabets and dash
$ #End of string. Not necessary as the first check (?=.{6,16}$) itself does that
bool IsValid(string userName)
{
return userName.Length >= 6 && userName.Length <= 16 && userName.Count(s => char.IsLetter(s)) >= 4;
}
It simpler not to use regular expressions.
And as known you can use other char.Is[something] functions if you need it
Related
In a recent scenario I wanted to extract the very last part of a vector of url's.
Eg.
> urls <- c('https::abc/efg/hij/', 'https::abc/efg/hij/lmn/', 'https::abc/efg/hij/lmn/opr/')
> rs <- regexpr("([^/])*(?=/$)", urls, perl = TRUE)
> substr(urls, rs, rs + attr(rs, 'match.length'))
[1] "hij/" "lmn/" "opr/"
which is somewhat simple to read. But I'd like to understand how I could do something similar by inverting the lookahead expression, eg. remove the second to last '/' and anything preceding (assuming that the string always ends with '/'). I can't seem to get the exact logic straight,
> gsub('([^/]|[/])(?!([^/]*/)$)', '', urls, perl = TRUE)
[1] "/hij" "/lmn" "/opr"
Basically I'm looking for the regexp logic that would return the result in the first example, but using only a single gsub call.
To get a match only, you could still use the lookahead construct:
^.*/(?=[^/]*/$)
^ Start of the string
.*/ Match until the last /
(?= Positive lookahead, assert what is on the right is
[^/]*/$ assert what is at the right is 0+ times any char except /, then match / at end of string
) Close lookahead
Regex demo | R example
For example
gsub('^.*/(?=[^/]*/$)', '', urls, perl = TRUE)
An option using a negative lookahead:
^.*/(?!$)
^ Start of string
.*/ Match the last /
(?!$) Negative lookahead, assert what is directly to the right is not the end of the string
Regex demo
The non-regex & very quick solution would be to use basename():
basename(urls)
[1] "hij" "lmn" "opr"
Or, for your case:
paste0(basename(urls), '/')
[1] "hij/" "lmn/" "opr/"
my prefered method is to replace the whole string with parts of the string, like so:
gsub("^.*/([^/]+/)$", "\\1", urls)
The "\\1" matches whatever was matched inside ().
So Basically I am replacing the whole string with the last part of the url.
Using Asp.net for regex.
I've written an extension method that I want to use to replace whole words - a word might also be a single special character like '&'.
In this case I want to replace '&' with 'and', and I'll need to use the same technique to reverse it back from 'and' to '&', so it must work for whole words only and not extended words like 'hand'.
I've tried a few variations for the regex pattern - started with '\bWORD\b' which didn't work at all for the ampersand, and now have '\sWORD\s' which almost works except that it also removes the spaces around the word, meaning that a phrase like "health & beauty" ends up as "healthandbeauty".
Any help appreciated.
Here's the extension method:
public static string ReplaceWord(this string #this,
string wordToFind,
string replacement,
RegexOptions regexOptions = RegexOptions.None)
{
Guard.String.NotEmpty(() => #this);
Guard.String.NotEmpty(() => wordToFind);
Guard.String.NotEmpty(() => replacement);
var pattern = string.Format(#"\s{0}\s", wordToFind);
return Regex.Replace(#this, pattern, replacement, regexOptions);
}
In order to match a dynamic string that should be enclosed with spaces (or be located at the start or end of string), you can use negative lookaheads:
var pattern = string.Format(#"(?<!\S){0}(?!\S)", wordToFind);
^^^^^^^ ^^^^^^
or even safer:
var pattern = string.Format(#"(?<!\S){0}(?!\S)", Regex.Escape(wordToFind));
^^^^^^^^^^^^^
The (?<!\S) lookbehind will fail the match if the word is not preceded with a non-whitespace character and (?!\S) lookahead will fail the match if the word is not followed with a non-whitespace character.
Is there any way to check in Xquery (A Xquery function) if an input string has only characters A-Z or numbers 0-9 and no other characters.
for example if the string is ABZ10 the function should return true and if the input string is 5& 123x it returns a false.
I am able to do it in java by simply using following.
inputstring.matches("^[0-9A-Z]+$"))
Use:
matches($vYourString, '^[A-Z0-9]+$')
I need a regular expression which can match a string with the following requirements:
Must be between 6 and 64 characters long
Cannot include the following symbols : #, &, ', <, >, !, ", /, #, $, %, +, ?, (, ), *, [ , ] , \ , { , }
Cannot contain spaces, tabs, or consecutive underscores, i.e. __
Cannot contain elements that imply an email address or URL, such as ".com", ".net", ".org", ".edu" or any variation (e.g. "_com" or "-com")
Cannot start with underscore '_', dash '-' or period '.'
Cannot contain the words "honey" or "allied"
Cannot contain single letter followed by numbers
This is better done with several regular expressions! And some of your conditions don't even need regexes (in fact, they would be counter productive).
use a string length function
use a function looking up for that character in your string;
match against _{2,} and \s
match against [._-](?:com|net|....)
use a string function looking for these characters at the first position, or ^[-._]
whole words? What about "calliedaaa"? If whole words, match against \b(?:honey|allied)\b, otherwise use a string lookup function
match against \w\d+
A customer asked me to prevent users from typing common passwords, but permit them to use only alphanumeric passwords.
Do you know a regular expression to use in the built in PasswordStrengthRegularExpression option?
Edit: I know is pretty vague, and that what I told the client. The definition is something like
Do not allow the same character more that 3 consecutive times.(1111, 2222, etc)
Do not allow ascending or descending trends (12345, abcde, 6543, etc.)
That's asking way too much from a regex. You could cover the repeated characters thing easily enough:
^(?:(.)(?!\1\1)){6,}$
But the only way to disallow runs of sequential characters would be to enumerate all the possibilities:
^(?:(?!123|234|345|456|567|678|789).)*$
...ad infinitum. I think the best you can do is require a complex mix of character types--for example, at least two each of uppercase letters, lowercase letters and digits:
^(?=(?:[^0-9]*[0-9]){2})
(?=(?:[^A-Z]*[A-Z]){2})
(?=(?:[^a-z]*[a-z]){2})
(?:([A-Za-z0-9])(?!\1\1)){6,}$
That will force the users to be a little creative.
How about this one?
passwordStrengthRegularExpression=" #\"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})"
Validates the password meets the following criteria:
Is greater than seven characters.
Contains at least one digit.
Contains at least one special
(non-alphanumeric) character.
http://msdn.microsoft.com/en-us/library/system.web.security.membership.passwordstrengthregularexpression.aspx
I'm not sure if a regular expression can handle the requirement, but a function just may be more readable anyway. Something like the below will eliminate anything with three consecutive equal characters or three consecutive characters that are follow an ascending or descending pattern of 1 (letters or numbers).
static bool IsPasswordRelativelyStrong(string input)
{
for (int i = 2; i < input.Length; i++)
{
if (input[i] == input[i - 1] - 1 && input[i - 1] == input[i - 2] - 1)
return false;
else if (input[i] == input[i - 1] + 1 && input[i - 1] == input[i - 2] + 1)
return false;
else if (input[i] == input[i - 1] && input[i - 1] == input[i - 2])
return false;
}
return true;
}
So given the following array
string[] passwords = { "123456", "abcde", "654321", "111223", "11223344" };
Only the final one passes. The function could be expanded to consider whether or not you allow and/or require non-alphanumeric characters and whether a password must exceed a minimum length requirement.
You can assert a minimum level of complexity; e. g. "at least one uppercase, one lowercase letter, one digit, minimum length 6 characters, only alphanumeric characters" could be written as
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9]{6,}$
try this:
passwordStrengthRegularExpression="^\S*([a-zA-Z0-9]{1,10})$"