I trying to validate 5 comma separated email id in one regular expression.
I currntly using below regex
^([\w+-.%]+#[\w-.]+\.[A-Za-z]{2,4},?)+$
This is valid for one email id.
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.
First of all, fix the pattern: - in between two chars inside a character class forms a range. So, the email part of your regex should be [-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4} (note the position of - in the first character class, in the second, it is OK to put it between a shorthand character class \w and the next char).
Next, to match 1 to 5 comma-separated emails, you need to match the first one, and then match 0 to 4 emails. And add anchors around the pattern to make sure the pattern matches the whole string:
^[-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4}(?:,[-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4}){0,4}$
Basically, ^<EMAIL>(?:,<EMAIL>){0,4}$:
^ - start of string
<EMAIL> - an email pattern of yours
(?: - start of a non-capturing group acting as a container for a sequence of patterns:
, - a comma
<EMAIL> - an email pattern of yours
){0,4} - zero to four occurrences of these sequences above
$ - end of string.
Another idea is to split with , and then validate:
var s = "abc#gg.com,abc2#gg.com,abc3#gg.com,abc4#gg.com,abc5#gg.com";
var re = /^[-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4}$/;
var items = s.split(",");
if (items.length <= 5 && items.filter(function(x) { return re.test(x); }).length === items.length ) {
console.log("VALID => ", items);
} else {
console.log("INVALID!");
}
Below regex for javaScript you can use for multiple comma separated email id, hope this work for you
/^(\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}\s*?,?\s*?)+$/
Related
I need a regex which satisfies the following conditions.
1. Total length of string 300 characters.
2. Should start with &,-,/,# only followed by 3 or 4 alphanumeric characters
3. This above pattern can be in continuous string upto 300 characters
String example - &ACK2-ASD3#RERT...
I have tried repeating the group but unsuccessful.
(^[&//-#][A-Za-z0-9]{3,4})+
That is not working ..just matches the first set
You may validate the string first using /^(?:[&\/#-][A-Za-z0-9]{3,4})+$/ regex and checking the string length (using s.length <= 300) and then return all matches with a part of the validation regex:
var s = "&ACK2-ASD3#RERT";
var val_rx = /^(?:[&\/#-][A-Za-z0-9]{3,4})+$/;
if (val_rx.test(s) && s.length <= 300) {
console.log(s.match(/[&\/#-][A-Za-z0-9]{3,4}/g));
}
Regex details
^ - start of string
(?:[&\/#-][A-Za-z0-9]{3,4})+ - 1 or more occurrences of:
[&\/#-] - &, /, # or -
[A-Za-z0-9]{3,4} - three or four alphanumeric chars
$ - end of string.
See the regex demo.
Note the absence of g modifier with the validation regex used with RegExp#test and it must be present in the extraction regex (as we need to check the string only once, but extract multiple occurrences).
You're close. Add the lookahead: (?=.{0,300}$) to the start to make it satisfy the length requirement and do it with pure RegExp:
/(?=.{0,300}$)^([&\-#][A-Za-z0-9]{3,4})+$/.test("&ACK2-ASD3#RERT")
You can try the following regex.
const regex = /^([&\/\-#][A-Za-z0-9]{3,4}){0,300}$/g;
const str = `&ACK2-ASD3#RERT`;
if (regex.test(str)) {
console.log("Match");
}
I need to match 5 occurrences of comma separated currency values.
I do have this reg ex that does the job but I think that's not the great way to do it.
^(\$[0-9]{1,3}(?:[,.]?[0-9]{3})*(?:\.[0-9]{2})?,\s?){4}(\$[0-9]{1,3}(?:[,.]?[0-9]{3})*(?:\.[0-9]{2})?)$
P.S. I had to split the expression into matching, 4 comma separated occurrences and 1 to sniff out trailing comma (I don't think that's the way to do it)
Some of the valid matching inputs could be,
$200,000,$525,$60000,$120,000,$65,456 (space between currency values is optional)
$200,000, $525, $60000,$120,000, $65,456
Some of the invalid input values,
$200,000,$525,$60000,$120,000,$65,456, (Trailing comma)
$200,000,,$525,$60000.$120,000,$65,456,, etc
Any pointers would be greatly appreciated.
Edit: The solution I am looking at is a pure reg ex solution (better than what I have written above), so that I can fire validations as soon as erroneous inputs are entered by the user.
Update
If you want to match while validating prices you could do this which follows:
Including both dot and comma for formatting prices
Max one space character between prices
^\$\d+([,.]\d{3})*( ?, ?\$\d+([,.]\d{3})*){4}$
Live demo
Breakdown:
^ Match start of input string (or line if m flag is set)
\$\d+ Match a $ that preceds a number of digits
( Start of grouping (#1)
[,.]\d{3} Match a period or comma that preceds 3 digits
)* End of grouping (#1), match at least zero time
( Start of grouping (#2)
?, ? Match a comma surrounded by optional spaces (one space at either side)
\$\d+ Match a $ that preceds a number of digits
([,.]\d{3})* Match a period or comma that preceds 3 digits (thousand separator), match at least zero time
){4} End of grouping (#2), repeat exactly 4 times
$ End of input string (or line if m flag is set)
JS code:
var re = /^\$\d+([,.]\d{3})*( ?, ?\$\d+([,.]\d{3})*){4}$/g;
var prices = ['$200,000,$525,$60000,$120,000,$65,456',
'$200,000, $525, $60000,$120,000, $65,456',
'$200,000,$525,$60000,$120,000,$65,456, ',
'$200,000,,$525,$60000.$120,000,$65,456,,'];
prices.forEach(function(s) {
console.log(s + " => " + Boolean(s.match(re)))
})
This regex is a simpler version of what you're trying to achieve:
^(?:\$\d{1,3}(?:,?\d{3})*[,.] ?){4}\$\d{1,3}(?:,?\d{3})*$
-------------------------------
The underlined part matches 4 "prices" as you've defined, followed by a dot/comma and an optional space.
The rest matches the last "price".
Please let me know if something is unclear
The most prevalent character to base the pattern on is \$ (escaped), whether it is the first character of the string or preceded by a comma (optionally followed by whitespace), that is done using (?:^|,)\s*. After that you want any number of digits, which is \d+, optionally followed by a comma which is immediately followed by digits again; ,\d+.
Combining these, you'd get; /(?:^|,)\s*(\$\d+(?:,\d+)?)/g
const pattern = /(?:^|,|\.)\s*(\$\d+(?:,\d+)?)/g;
const test = [
'$200,000,$525,$60000,$120,000,$65,456',
'$200,000, $525, $60000,$120,000, $65,456',
'$200,000,$525,$60000,$120,000,$65,456,',
'$200,000,,$525,$60000.$120,000,$65,456,,',
];
const matches = test.reduce((carry, string) => {
let match = null;
while (match = pattern.exec(string)) {
carry.push(match[1]);
}
return carry;
}, []);
console.log(matches);
Added the extra examples from the modified question, including the . which now appeared as separator ($200,000,,$525,$60000.$120,000,$65,456,,) and modified the pattern in the example to account for this.
I'm trying to create a regex using javascript that will allow names like abc-def but will not allow abc-
(hyphen is also the only nonalpha character allowed)
The name has to be a minimum of 2 characters. I started with
^[a-zA-Z-]{2,}$, but it's not good enough so I'm trying something like this
^([A-Za-z]{2,})+(-[A-Za-z]+)*$.
It can have more than one - in a name but it should never start or finish with -.
It's allowing names like xx-x but not names like x-x. I'd like to achieve that x-x is also accepted but not x-.
Thanks!
Option 1
This option matches strings that begin and end with a letter and ensures two - are not consecutive so a string like a--a is invalid. To allow this case, see the Option 2.
^[a-z]+(?:-?[a-z]+)+$
^ Assert position at the start of the line
[a-z]+ Match any lowercase ASCII letter one or more times (with i flag this also matches uppercase variants)
(?:-?[a-z]+)+ Match the following one or more times
-? Optionally match -
[a-z]+ Match any ASCII letter (with i flag)
$ Assert position at the end of the line
var a = [
"aa","a-a","a-a-a","aa-aa-aa","aa-a", // valid
"aa-a-","a","a-","-a","a--a" // invalid
]
var r = /^[a-z]+(?:-?[a-z]+)+$/i
a.forEach(function(s) {
console.log(`${s}: ${r.test(s)}`)
})
Option 2
If you want to match strings like a--a then you can instead use the following regex:
^[a-z]+[a-z-]*[a-z]+$
var a = [
"aa","a-a","a-a-a","aa-aa-aa","aa-a","a--a", // valid
"aa-a-","a","a-","-a" // invalid
]
var r = /^[a-z]+[a-z-]*[a-z]+$/i
a.forEach(function(s) {
console.log(`${s}: ${r.test(s)}`)
})
You can use a negative lookahead:
/(?!.*-$)^[a-z][a-z-]+$/i
Regex101 Example
Breakdown:
// Negative lookahead so that it can't end with a -
(?!.*-$)
// The actual string must begin with a letter a-z
[a-z]
// Any following strings can be a-z or -, there must be at least 1 of these
[a-z-]+
let regex = /(?!.*-$)^[a-z][a-z-]+$/i;
let test = [
'xx-x',
'x-x',
'x-x-x',
'x-',
'x-x-x-',
'-x',
'x'
];
test.forEach(string => {
console.log(string, ':', regex.test(string));
});
The problem is that the first assertion accepts 2 or more [A-Za-z]. You will need to modify it to accept one or more character:
^[A-Za-z]+((-[A-Za-z]{1,})+)?$
Edit: solved some commented issues
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('xggg-dfe'); // Logs true
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('x-d'); // Logs true
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('xggg-'); // Logs false
Edit 2: Edited to accept characters only
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('abc'); // Logs true
Use this if you want to accept such as A---A as well :
^(?!-|.*-$)[A-Za-z-]{2,}$
https://regex101.com/r/4UYd9l/4/
If you don't want to accept such as A---A do this:
^(?!-|.*[-]{2,}.*|.*-$)[A-Za-z-]{2,}$
https://regex101.com/r/qH4Q0q/4/
So both will accept only word starting from two characters of the pattern [A-Za-z-] and not start or end (?!-|.*-$) (negative lookahead) with - .
Try this /([a-zA-Z]{1,}-[a-zA-Z]{1,})/g
I suggest the following :
^[a-zA-Z][a-zA-Z-]*[a-zA-Z]$
It validates :
that the matched string is at least composed of two characters (the first and last character classes are matched exactly once)
that the first and the last characters aren't dashes (the first and last character classes do not include -)
that the string can contain dashes and be greater than 2 characters (the second character class includes dashes and will consume as much characters as needed, dashes included).
Try it online.
^(?=[A-Za-z](?:-|[A-Za-z]))(?:(?:-|^)[A-Za-z]+)+$
Asserts that
the first character is a-z
the second is a-z or hyphen
If this matches
looks for groups of one or more letters prefixed by a hyphen or start of string, all the way to end of string.
You can also use the I switch to make it case insensitive.
I am preparing a regular expression validation for text box
where person can enter only 0-9,*,# each with comma seprated and non repeative.
I prepared this
if( ( incoming.GET_DTMF_RESPONSE.value.match(/[0-9*#]\d*$/)==null ) )
alert("DTMF WRONG"
where incoming is functions back and GET_DTMF_RESPONSE is textbox name
I am not good in Regex..it is accepting 0-9 and * and # thats good
but it is accepting a-z also
i want it to make non repeative numbers and no alphabet and no special character excepting #,*
Let me know how to do this
How about this regex
^(?!.*,$|.*\d{2,})(?:([\d*#]),?(?!.*\1))+$
For each value separated by comma am capturing it into group1 and then am checking if it occurs ahead using \1(backreference)
^ marks the beginning of string
(?!.*,$|.*\d{2,}) is a lookahead which would match further only if the string doesn't end with , or has two or more digits
In (?:([\d*#]),?(?!.*\1))+ a single [\d*#] is captured in group 1 and then we check whether there is any occurrence of it ahead in the string using (?!.*\1). \1 refers to the value in group 1.This process is repeated for each such value using +
$ marks the end of string
For example
for Input
1,2,4,6,2
(?!.*,$|.*\d{2,}) checks if the string doesn't end with , or has two or more digits
The above lookahead only checks for the pattern but doesn't match anything.So we are still at the beginning of string
([\d*#]) captures 1 in group 1
(?!.*\1) checks(not match) for 1 anywhere ahead.Since we don't find one,we move forward
Due to + we would again do the same thing
([\d*#]) would now capture 2 in group 1
(?!.*\1) checks(not match) for 2 anywhere ahead.Since we find it,we have failed matching the text
works here
But you better use non regex solution as it would be more simple and maintainable..
var str="1,2,4,6,6";
str=str.replace(/,/g,"");//replace all , with empty string
var valid=true;
for(var i=0;i<str.length-1;i++)
{
var temp=str.substr(i+1);
if(temp.indexOf(str[i])!=-1)valid=false;
}
//valid is true or false depending on input
You can use this:
^(?:([0-9#*])(?!(?:,.)*,\1)(?:,|$))+$
I am still a beginner :)
I need to get a substring ignoring the last section inside [] (including the brackets []), i.e. ignore the [something inside] section in the end.
Note - There could be other single occurances of [ in the string. And they should appear in the result.
Example
Input of the form -
1 checked arranged [1678]
Desired output -
1 checked arranged
I tried with this
var item = "1 checked arranged [1678]";
var parsed = item.match(/([a-zA-Z0-9\s]+)([(\[d+\])]+)$/);
|<-section 1 ->|<-section 2->|
alert(parsed);
I tried to mean the following -
section 1 - multiple occurrences of words (containing literals and nos.) followed by spaces
section 2 - ignore the pattern [something] in the end.
But I am getting 1678],1678,] and I am not sure which way it is going.
Thanks
OK here is the problem in your expression
([a-zA-Z0-9\s]+)([(\[d+\])]+)$
The Problem is only in the last part
([(\[d+\])]+)$
^ ^
here are you creating a character class,
what you don't want because everything inside will be matched literally.
((\[d+\])+)$
^ ^^
here you create a capturing group and repeat this at least once ==> not needed
(\[d+\])$
^
here you want to match digits but forgot to escape
That brings us to
([a-zA-Z0-9\s]+)(\[\d+\])$
See it here on Regexr, the complete string is matched, the section 1 in capturing group 1 and section 2 in group 2.
When you now replace the whole thing with the content of group 1 you are done.
You could do this
var s = "1 checked arranged [1678]";
var a = s.indexOf('[');
var b = s.substring(0,a);
alert(b);
http://jsfiddle.net/jasongennaro/ZQe6Y/1/
This s.indexOf('['); checks for where the first [ appears in the string.
This s.substring(0,a); chops the string, from the beginning to the first [.
Of course, this assumes the string is always in a similar format
var item = '1 check arranged [1678]',
matches = item.match(/(.*)(?=\[\d+\])/));
alert(matches[1]);
The regular expression I used makes use of a positive lookahead to exclude the undesired portion of the string. The bracketed number must be a part of the string for the match to succeed, but it will not be returned in the results.
Here you can find how to delete stuff inside square brackets. This will leave you with the rest. :)
Regex: delete contents of square brackets
try this if you only want to get rid of that [] in the end
var parsed = item.replace(/\s*\[[^\]]*\]$/,"")
var item = "1 checked arranged [1678]";
var parsed = item.replace(/\s\[.*/,"");
alert(parsed);
That work as desired?
Use escaped brackets and non-capturing parentheses:
var item = "1 checked arranged [1678]";
var parsed = item.match(/([\w\s]+)(?:\s+\[\d+\])$/);
alert(parsed[1]); //"1 checked arranged"
Explanation of regex:
([\w\s]+) //Match alphanumeric characters and spaces
(?: //Start of non-capturing parentheses
\s* //Match leading whitespace if present, and remove it
\[ //Bracket literal
\d+ //One or more digits
\] //Bracket literal
) //End of non-capturing parentheses
$ //End of string