How to combine a few regex expressions in JavaScript? - javascript

I have a few requirements to validate email address and have a few regex expressions for that purpose.
But how I can combine them to one regex to make it work correctly?
(?=^\\S+#\\S+\\.\\S+$)
Dotted email address
(?=^[A-Za-z0-9#$\\._-]+$)
allows alphanumeric, '#', '.', '_', '-'
(?=^[A-Za-z0-9].*$)
cannot start with special character
(?=^.{5,100}$)
between 5 and 100 characters
(?=^((?!([0-9]{9,}\\1)).)*$)
Not nine or more numbers
(^(?!.*[#].*[#]).*$)
One at mark

Try concatenating your expressions:
const emailRegex = /(?=^\S+#\S+\.\S+$)(?=^[A-Za-z0-9#$\._-]+$)(?=^[A-Za-z0-9].*$)(?=^.{5,100}$)(?=^((?!([0-9]{9,}\1)).)*$)(^(?!.[#].[#]).*$)/;

There are a lot of custom rules using lookaheads, from which you can omit a few by matching instead of asserting.
^(?=\S{5,100}$)(?!\S*\d{9})[A-Za-z0-9][A-Za-z0-9$\\._-]*#[A-Za-z0-9$\\._-]+\.[A-Za-z0-9]+$
^ Start of string
(?=\S{5,100}$) Assert 5-100 non whitspace chars
(?!\S*\d{9}) Assert not 9 consecutive digits in the string
[A-Za-z0-9] Match a single char A-Z a-z or a digit
[A-Za-z0-9$\\._-]* Optionally repeat what is listed in the character class
# Match an # char (Note that you can omit the square brackets [#])
[A-Za-z0-9$\\._-]+ Match 1+ times any of the listed in the character class
\.[A-Za-z0-9]+ Match a . and 1+ times any of the listed in the character class
$ End of string
Regex demo

Related

typescript Yup validation or condition with regex using matches problem

I'm trying to make sure only one type of special character (semi-colon, comma, or space) is used in a string.
Valid case:
Can contain alphanumeric letters and numbers
Can contain special characters : / .
Can contain only one type of special characters from: space, semi-colon or comma in the string
e.g this should match as it only uses one type of special character (semi-colon):
https://hello.com/example1;https://hello.com.com/example2;https://hello.com.com/example3
This should fail as it mixes two types of special characters (space and semi-colon)
https://hello.com/example1; https://hello.com.com/example2 ;https://hello.com.com/example3
This is my code:
const myValidation = yup
.string()
.matches(/^([A-Za-z0-9://,\\.]|[A-Za-z0-9:// \\.]|[A-Za-z0-9://;\\.])+$/, 'Please separate each with a comma, space or semicolon')
.required();
When i only have /^([A-Za-z0-9://,\\.]+$/ it works correctly to only match the string if it has a only a comma as special character:
https://hello.com/example1,https://hello.com.com/example2,https://hello.com.com/example3
but as soon as i add the other or conditions /^([A-Za-z0-9://,\\.]|[A-Za-z0-9:// \\.]|[A-Za-z0-9://;\\.])+$/ it starts allowing for semi-colon and space and comma special characters in the string at the same time (the invalid case)
For the valid cases, you can use a capture group with a backreference \1 to make sure that the "special character" is the same delimiter between the matches
^[A-Za-z0-9:/.]+(?:([ ,;])[A-Za-z0-9:/.]+(?:\1[A-Za-z0-9:/.]+)*)?$
The pattern matches:
^ Start of string
[A-Za-z0-9:/.]+ Match 1+ of the allowed characters
(?: Non capture group to match as a whole part
([ ,;]) Capture group 1, match one of the delimiters
[A-Za-z0-9:/.]+ Match 1+ of the allowed characters
(?:\1[A-Za-z0-9:/.]+)* Optionally repeat a backreference to the same delimiter and again 1+ of the allowed characters
)? Close the non capture group and make it optional
$ End of string
See a regex demo.
const regex = /^[A-Za-z0-9:/.]+(?:([ ,;])[A-Za-z0-9:/.]+(?:\1[A-Za-z0-9:/.]+)*)?$/;
[
"https://hello.com/example1;https://hello.com.com/example2;https://hello.com.com/example3",
"https://hello.com/example1; https://hello.com.com/example2 ;https://hello.com.com/example3",
"https://hello.com/example1"
].forEach(s =>
console.log(`${regex.test(s)} --> ${s}`)
);
If there should be at least a single delimiter present, you could shorten the pattern to:
^[A-Za-z0-9:/.]+([ ,;])[A-Za-z0-9:/.]+(?:\1[A-Za-z0-9:/.]+)*$
If the strings should start with http:// or https:// you could use:
^https?:\/\/[A-Za-z0-9:/.]+(?:([ ,;])https?:\/\/[A-Za-z0-9:/.]+(?:\1[A-Za-z0-9:/.]+)*)?$
See another regex demo.
Is only one
function isOnlyOne() {
let s = "zy,,aemnofgbcjkhilpqasdfrstuvrhfwx";
console.log([...new Set(s.split("").filter(e => e.match(/[;, ]/)))].length==1);
//return [...new Set(s.split("").filter(e => e.match(/[a-z]/)))].length==26;
}

JavaScript regex with below rules

Need to create a regex for a string with below criteria
Allowable characters:
uppercase A to Z A-Z
lowercase a to z a-z
hyphen `
apostrophe '
single quote '
space
full stop .
numerals 0 to 9 0-9
Validations:
Must start with an alphabetic character a-zA-Z or apostrophe
Cannot have consecutive non-alpha characters except for a full stop followed by a space.
The regex I have from the previous question in this forum. Business came back and want to allow string starting with apostrophe along with [a-zA-Z]. This break some previous validations.
eg: a1rte is valid
'tyer4 is valid
'4rt is invalid
^(?!.*[0-9'`\.\s-]{2})[a-zA-Z][a-zA-Z0-9-`'.\s]+$
Please advise.
You might use
^(?=[a-zA-Z0-9`'. -]+$)(?!.*[0-9'` -]{2})[a-zA-Z'][^\r\n.]*(?:\.[ a-z][^\r\n.]*)*$
Explanation
^ Start of string
(?=[a-zA-Z0-9`'. -]+$) Assert only allowed characters
(?!.*[0-9'` -]{2}) Assert not 2 consecutive listed characters
[a-zA-Z'] Match either a char a-zA-Z or apostrophe
[^\r\n.]* Optionally match any char except a newline or a dot
(?:\.[ a-z][^\r\n.]*)* Optionally repeat matching a dot only followed by a space or char a-z
$ End of string
Regex demo

Regular expression to validate a string starts with a char and contains allowed chars

I need help with my regular expression written in javascript.
I have tried using the regularExpression generator online, and the best i can come up with is the this:
^[a-z.-]{0,50}$
The expression must validate the following
String first char MUST start with a-z (no alpha)
String can contain any char in range a-z (no alpha), 0-9 and the characters dash "-" and dot "."
String can be of max length 50 chars
Examples of success strings
username1
username.lastname
username-anotherstring1
this.is.also.ok
No good strings
1badusername
.verbad
-bad
also very bad has spaces
// Thanks
Almost (assuming "no alpha" means no uppercase letters)
https://regex101.com/r/O9hvLP/3
^[a-z]{1}[a-z0-9\.-]{0,49}$
The {1} is optional, I put it there for descriptive reasons
I think this should cover what you want
^[a-z][a-z0-9.-]{0,49}$
That is starts a-z but then has 0-49 of a-z, 0-9 or .-
Live example: https://regexr.com/5k8eu
Edit: Not sure if you intended to allow upper and lowercase, but if you did both character classes could add A-Z as well!
If the . and - can not be at the end, and there can not be consecutive ones, another option could be:
^[a-z](?=[a-z0-9.-]{0,49}$)[a-z0-9]*(?:[.-][a-z0-9]+)*$
Explanation
^ Start of string
[a-z] Match a single char a-z
(?=[a-z0-9.-]{0,49}$) Assert 0-49 chars to the right to the end of string
[a-z0-9]* Match optional chars a-z0-9
(?:[.-][a-z0-9]+)* Optionally match either . or - and 1+ times a char a-z0-9
$ End of string
Regex demo

Regex to not allow special character without prefix or suffix

I was writing regex for the following validate a string. I wrote the following regex.
^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}$
it validates for
No space in beginning.
no two consecutive space allowed.
The problem is it allows a single special character. it should not allow a special character unless it is suffixed or prefixed with alpha-numeric character.
Examples:
# -> not allowed.
#A or A# or A2 or 3A is allowed.
One option is to assert that the string does not contain a single "special" char or 2 special chars next to each other using a negative lookahead.
^(?!.*[^a-zA-Z0-9\s][^a-zA-Z0-9\s])(?!.*(?:^| )[^a-zA-Z0-9\s](?!\S))\S+(?: \S+)*$
Explanation
^ Start of string
(?! Negative lookahead, assert that what is at the right does not contain
.*[^a-zA-Z0-9\s][^a-zA-Z0-9\s] match 2 chars other than a-zA-Z0-9 or a whitespace char next to each other
) Close lookahead
(?! Negative lookahead, assert that what is at the right does not contain
.*(?:^| )[^a-zA-Z0-9\s](?!\S) Match a single char other than a-zA-Z0-9 or a whitespace char
) Close lookahead
\S+(?: \S+)* Match 1+ non whitespace chars and optionally repeat a space and 1+ non whitespace chars
$ End of string
Regex demo
Please omit the '$' symbol from the regex because it represents the end of the sentence.
^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}
So when applying the above regex to the following, it finds only '# '.
#A A# A2 3A

Regex to disallow certain characters in specific sequence

I have a regular expression that allows only letters, numbers, spaces or hyphens. However, I'd like to disallow the user to do the following:
hello--world Have more than one hyphen sitting next to each other
--hello Have a hyphen in the beginning. It must have a number or letter first
How do I accomplish this? My current regex looks like this:
let alphanumericTest = new RegExp("^\s*([0-9a-zA-Z- ]*)\s*$");
You can try this regex expression. ^\s*[0-9a-zA-Z](?:(?!--)[0-9a-zA-Z- ])*$
This is a demo.
You could make you match a bit more efficient without using a negative lookahead for matching non consecutive hyphens using repeating groups which can optionally start with an hyphen after the first word.
^[ ]*[0-9a-zA-Z]+(?:-[0-9a-zA-Z]+)*-?(?:[ ]+-?(?:[0-9a-zA-Z]+-?)*)*$
(Used [ ] to match a space for clarity)
Explanation
^ Start of string
[ ]* Match 0+ spaces
[0-9a-zA-Z]+ Match 1+ times any of the listed
(?:-[0-9a-zA-Z]+)* Repeat 0+ times matching a hyphen and 1+ what is listed
-? Match optional hyphen
(?: Non capturing group
[ ]+-?(?:[0-9a-zA-Z]+-?)* Match 1+ spaces, optional hyphen, repeat 0+ times what is listed and optional hyphen
)* Close outer non capturing group and repeat 0+ times
$ End of string
Regex demo
Try:
let alphanumericTest = new RegExp("^(?!-)(?!.*--)[0-9a-zA-Z- ]+(?<!-)$");
This checks that the first character is not a - and that there are no consecutive --s anywhere in the string

Categories

Resources