if (Regex.IsMatch(text, @"
# Validate username with 5 constraints.
^ # Anchor to start of string.
# 1- only contains alphanumeric characters , underscore and dot.
# 2- underscore and dot can't be at the end or start of username,
# 3- underscore and dot can't come next to each other.
# 4- each time just one occurrence of underscore or dot is valid.
(?=[A-Za-z0-9]+(?:[_.][A-Za-z0-9]+)*$)
# 5- number of characters must be between 8 to 20.
[A-Za-z0-9_.]{8,20} # Apply constraint 5.
$ # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace))
{
// Successful match
} else {
// Match attempt failed
}
^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$
└─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘
│ │ │ │ no _ or . at the end
│ │ │ │
│ │ │ allowed characters
│ │ │
│ │ no __ or _. or ._ or .. inside
│ │
│ no _ or . at the beginning
│
username is 8-20 characters long
If your browser raises an error due to lack of negative look-behind support, use the following alternative pattern:
function isUserName(val){
let regUser=/^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$/;
if(!regUser.test(val)){
return 'Name can only use letters,numbers, minimum length is 8 characters';
}
}
const regex = /^moe_(app|lab)[A-Za-z0-9]{3}$/;
const str = `moe_app_baa`;
let m;
if ((m = regex.exec(str)) !== null) {
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Stumbled upon this question in another one. Seems not necessary to use that many lookarounds.
Following a bit shorter pattern with use of \w which is a short for word character and commonly preset to [A-Za-z0-9_]. To get rid of the underscore, [^\W_] can be used to match [A-Za-z0-9].