How can I match only numerical email addresses?
I'm testing against the following email addresses:
12345839223#gmail.com <-- want this
38482934934#gmail.com <-- want this
abcaasd#gmail.com <-- don't want this
asdasd123#gmail.com <-- don't want this
123asdasd#gmail.com <-- don't want this
I tried the following regex, but it matches some addresses with letters.
([0-9])+(#+)
The regex /^\d+(?=#)/ will achieve this for you. As you can see from the image below, it looks for the start of the line followed by one or more digits followed by an "#" symbol.
Here's a RegEx101 test case for reference
var emails = [
'12345839223#gmail.com',
'38482934934#gmail.com',
'abcaasd#gmail.com',
'asdasd123#gmail.com',
'123asdasd#gmail.com'
];
function emailNum(email) {
return (/^\d+(?=#)/.exec(email)||[false])[0];
// return the match if it exists or false
}
for(var i in emails) document.write(emails[i]+': '+emailNum(emails[i])+'<br>');
In Javascript, you could have a function like this:
function isNumberEmail(email) {
return /^\d+#.*\./.test(email)
}
emailsToTest = ["12345839223#gmail.com",
"38482934934#gmail.com",
"abcaasd#gmail.com",
"asdasd123#gmail.com",
"123asdasd#gmail.com"]
emailsToTest.forEach(function(email) {
document.write(email + " - " + isNumberEmail(email))
document.write("<br>")
})
You can use the following to test if the first part of the email is a number:
function test( val ) {
var first = val.match(/^([^#]+)/g)[0];
return /^\d+$/g.test(first);
}
console.log(test('12345#email.com'));
console.log(test('12345678#email.com'));
console.log(test('abc12345#email.com'));
console.log(test('12345abc#email.com'));
I think this will work, wouldn't mind if someone can verify. Adds # to capture group
/([1-9][0-9]*)+(#)/g
Edit: ^\d+# works as per #dustmouse's comment
Related
So I have this list of emails:
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
It comes through as a string, sometimes with a return character at the end of each line, sometimes it doesn't. All I want to be able to do is pull out each email from the string using regex.
So I've got this regex exp from here:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
How do I get it to match many email addresses and return me each individual email?
I do not want to split on a return character, I can't always garauntee that it will be that character that will split the list up. These emails are pasted in from the users clipboard. If it were that easy, I wouldn't have asked ;)
It comes through as a string, with a return character at the end of
each line.
Then just split the string on newlines ?
var email_array = str.split("\n");
Here's a VERY simple way to do it.
/([^;:<>!?\n]+\#[^;:<>!?\n]+\.[^;:<>!?\n]+)/gmi
Explanation:
The [^;:<>!?\n] matches everything EXCEPT those characters. So [^;:<>!?\n]+ just means match everything but these as many times as needed.
Then match an # symbol.
Then match as many of NOT these ([^;:<>!?\n]) as needed again.
Then match a literal dot (.).
Then DON'T match these ([^;:<>!?\n]) again.
The gmis at the end are called flags. They mean:
g means global. Match this RegEx over and over.
m means multi-line. Don't stop at the end of the first line of emails.
i means insensitive. Don't worry about the upper and lower cases.
Demonstrations here: https://regex101.com/r/aC5cK2/1
So I have re work the answer to incorporate what #adeneo said:
$scope.pasteThis = function(e) {
var emails = e.clipboardData.getData('text/plain');
var emailArray = emails.split(/(\n|\s|,)/);
angular.forEach(emailArray, function (e) {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+#[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
if (EMAIL_REGEXP.test(e)) {
if (!contains($scope.emailAddresses, e)) {
$scope.emailAddresses.push(e);
}
}
});
}
function contains(arr, el) {
var found = false;
angular.forEach(arr, function(e) {
if (e == el) {
found = true;
}
});
return found;
}
So EMAIL_REGEXP is from the Angular source code. I use that in other places so it is very appropriate to use it here (consistency).
This function makes sure that after the emails are split, each one is a valid email address. This means that no mess can get through.
I want to validate following text using regular expressions
integer(1..any)/'fs' or 'sf'/ + or - /integer(1..any)/(h) or (m) or (d)
samples :
1) 8fs+60h
2) 10sf-30m
3) 2fs+3h
3) 15sf-20m
i tried with this
function checkRegx(str,id){
var arr = strSplit(str);
var regx_FS =/\wFS\w|\d{0,9}\d[hmd]/gi;
for (var i in arr){
var str_ = arr[i];
console.log(str_);
var is_ok = str_.match(regx_FS);
var err_pos = str_.search(regx_FS);
if(is_ok){
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
}else{
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
but it is not working
please can any one help me to make this correct
This should do it:
/^[1-9]\d*(?:fs|sf)[-+][1-9]\d*[hmd]$/i
You were close, but you seem to be missing some basic regex comprehension.
First of all, the ^ and $ just make sure you're matching the entire string. Otherwise any junk before or after will count as valid.
The formation [1-9]\d* allows for any integer from 1 upwards (and any number of digits long).
(?:fs|sf) is an alternation (the ?: is to make the group non-capturing) to allow for both options.
[-+] and [hmd] are character classes allowing to match any one of the characters in there.
That final i allows the letters to be lowercase or uppercase.
I don't see how the expression you tried relates anyhow to the description you gave us. What you want is
/\d+(fs|sf)[+-]\d+[hmd]/
Since you seem to know a bit about regular expressions I won't give a step-by-step explanation :-)
If you need exclude zero from the "integer" matches, use [1-9]\d* instead. Not sure whether by "(1..any)" you meant the number of digits or the number itself.
Looking on the code, you
should not use for in enumerations on arrays
will need string start and end anchors to check whether _str exactly matches the regex (instead of only some part)
don't need the global flag on the regex
rather might use the RegExp test method than match - you don't need a result string but only whether it did match or not
are not using the err_pos variable anywhere, and it hardly will work with search
function checkRegx(str, id) {
var arr = strSplit(str);
var regx_FS = /^\d+(fs|sf)[+-]\d+[hmd]$/i;
for (var i=0; i<arr.length; i++) {
var str = arr[i];
console.log(str);
if (regx_FS.test(str) {
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
} else {
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
Btw, it would be better to separate the validation (regex, array split, iteration) from the output (id, jQuery, logs) into two functions.
Try something like this:
/^\d+(?:fs|sf)[-+]\d+[hmd]$/i
I'm definitely a newbie and am trying a practice project.
Its basically an anagram game where the user clicks on certain letters to put together a word.
I now need to check that it is actually a word. I've made a text file containing all the words in the dictionary (copied from someones website as its just a practice project). I've managed to get it so that if I can console.log the words.
function Searchtext(){
$.get('words.txt', function(data) {
console.log(data);
}, 'text');
}
Now I want to search the words to see if the player's answer ( a string which is declared in a variable called playeranswer ) is in the list. I don't need it to return the word, only whether it is there or not. N.B. it has to be exact so that for example if the user entered "ender" which isnt a word, it wont come back true because it finds the word "render". Maybe something with the .length will help?
How would I go about doing this?
Thanks for any help.
Since $.get is asynchronous, you'll have to set it up a little differently. I'd do this:
function Searchtext(name, callback) {
$.get('words.txt', function(data) {
data = data.split("\n");
var contains = (data.indexOf(name) > -1);
callback(contains);
}, 'text');
}
Depending on how the text file is setup, you might have to change .split("\n") (which splits up the words into an array, if they're each on a line) to .split(" ") (which splits up the words into an array, if they're separated by a space).
And you'd call it like:
SearchText(playername, function (matched) {
if (matched) {
// Name was in list
} else {
// Name wasn't in list
}
});
DEMO: http://jsfiddle.net/Fkr5B/
In the demo, I had to simulate the AJAX request.
I would use a regular expression (using a RegExp object) for this. Here is a simple example that tries to match a word in two different strings of words:
var word_to_match = 'ender';
var string_of_words = 'a string containing the word ender, this will match';
var second_string_of_words = 'a string that will not produce a match';
//use \b to match on word boundaries
var filter = new RegExp('\\b' + word_to_match + '\\b', 'gi');
if(string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
if(second_string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
You'll see the first if statement passes, while the second fails. A little reading might be required, but you should be able to expand this example to fit your use case.
You should first parse the data variable and place the words into an Array.
Then you can test if the user entered a valid word by checking if your Array contains that word.
var Dict = new Array("render", "bender", "word");
function isValid(word){
if(Dict.indexOf(word) == -1)
return false; //the word is not valid
return true; //the word is valid
}
I've made this simple script, hope it helps
$(document).ready(function(e) {
function parseData(data) {
$('#inpu').blur(function() {
var str_to_search = $.trim($('#inpu').val());
if(str_to_search.length) {
var search_res = data.search(str_to_search);
if(search_res != -1) {
alert('Word Valid!');
} else {
alert('Word no valid');
}
}
});
}
$.get('to_search.txt', parseData).fail(function() { alert('error');});
});
I need to check if a string represents a valid namespace format. A namespace is comprised of ids separated with dots. Each id starts with an alphabetic character and continues with an alphanumeric character.
Valid namespaces:
"com.company.package"
"com.company"
"com"
Invalid namespaces:
"1com.company.package"
"com.1company"
"com.com%any"
".com.company"
"com.company."
"com "
" com"
""
"."
"com..company"
Currently I use this simple regexp but it really don't check all of those invalid namespaces:
if( /^[\w\.]$/.test( namespaceStr ) ) {
//valid namespace
} else {
//invalid namespace
}
Any better suggestion for a small and efficient way to check if a string represents a valid namespace?
Here is a little jsfiddle that you can use for testing this regular expression: http://jsfiddle.net/bA85y/
Edit: This one should work for every case:
/^(?:[a-z]\d*(?:\.[a-z])?)+$/i
If you don't care about capturing groups even shorter:
/^([a-z]\d*(\.[a-z])?)+$/i
A little explanation:
^ // Start
( // Open group
[a-z]\d* // Must start by letter and may be followed by a number (greedy)
(\.[a-z])? // It may be followed by a dot only if it's followed by a letter (non-greedy)
)+ // Close group and match at least once so we get rid of empty values
$ // Ends, not allow any other characters
Demo: http://jsfiddle.net/elclanrs/5hnQV/
Try this pattern:
/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)*$/i
EDIT:
this is a reversion of #elclanrs jsfiddle
I think you are looking for this:
/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i
EDIT:
This one is a little better (with ?: and \d inspired by #HashemQolami and #elclanrs):
/^[a-z][a-z\d]*(?:\.[a-z][a-z\d]*)*$/i
And this one is shorter but does the same job:
/^[a-z](?:[a-z\d]*(?:\.[a-z])?)*$/i
And this one too, using lookahead to test that it doesn't end with a .:
/^(?!.*\.$)(?:[a-z][a-z\d]*\.?)+$/i
Please note that the selected answer doesn't work with "a.b.c" or in some cases with more than two levels.
UPDATE:
I've made a little (very basic) test:
var valid = [
"com.company.package",
"com.company",
"com.company1",
"com1.company1",
"a.b.c",
"a1.b.c3.d",
"a1.b2.c3.d4"];
var invalid = [
"1com.company.package",
"com.1company",
"com.com%any",
".com.company",
"com.company.",
"com ",
" com",
"",
".",
"com..company"];
function testRegex(regex, list)
{
var res=[];
for(var i=0; i<list.length; i++)
{
if(regex.test(list[i]))
res.push(list[i] + " ==> matched");
else
res.push(list[i] + " ==> NOT matched");
}
return res.join('<br>');
}
var regex = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i;
var html = "<p>VALID</p>";
html += testRegex(regex, valid);
html += "<p>INVALID</p>";
html += testRegex(regex, invalid);
document.write("<div>" + html + "</div>");
Based on #dionyziz answer this work:
/^[a-z]+(\.[a-z]+)*[^.\s]$/
The following regular expression will do what you need. It checks for an alphabetic string and then allows multiple other alphabetic strings separated by a dot.
/^[a-z]+(\.[a-z]+)*$/
I have a question for you that I can't seem to figure out on my own.
Let's say that I want to validate a users first name. Some can contain multiple parts like "John William" with a space in between. What I want to do is match the input to a regular expression that seeks out if the name contains any spaces at the beginning, or at the end.
Further more the regular expression should check if there are ONLY letters (a-z, both lower and upper case) in the name.
This is what I came up with so far:
/^\s+[A-z]+|[A-z]+\s+$/
But somehow this regular expression does not take any other characters (such as dash, underscore, ampersand, etc.) into notice. Basically all it does is tell me wether there are spaces at the beginning or at the end of the input.
Can anyone help me out here?
EDIT:
Here's the full code i'm using:
$(document).ready(function() {
$('#firstname, #lastname').bind('keyup blur', function() {
var _input = $(this);
var _illegal = Validate_Regexp(_input.val(), /^\s+[A-Za-z]+|[A-Za-z]+\s+$/);
if (_illegal == true) {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_red.png)',
});
} else {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_green.png)',
});
}
});
});
function Validate_Regexp($value, $regexp) {
return $regexp.test($value);
}
EDIT 2:
I'm going with Charlie's answer, however his answer forced me to have 2 parts of the name, instead of as much as I'd like.
I changed the code from:
var isLegal = /^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(stringToTest);
to:
var isLegal = /^[a-zA-Z]+(\s[a-zA-Z]+)*?$/.test(stringToTest);
I noticed that you are checking for strings that are illegal. Let's turn it around and check for a string that is valid:
var isValid = /^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(stringToTest);
Results:
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john doe"); // true
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john"); // true
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john d_oe"); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(" john doe "); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(" john doe"); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john doe "); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john "); // false
Translated to your existing code:
var isValid = Validate_Regexp(_input.val(), /^[a-zA-Z]+(\s+[a-zA-Z]+)?$/);
if (isValid) {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_blue.png)',
});
} else {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_red.png)',
});
}
You really don't care if there are leading or trailing spaces, or how many there are in between the names, all that stuff is very easy to manage without bothering the user.
So a suitable function might be:
function checkNames(s) {
// Remove excess spaces
s.replace(/(^\s*)|(\s*$)/g, '').replace(/\s+/g, ' ');
// Check remaining content
return /[a-z]+ [a-z]+/i.test(s);
}
But note that names can be hyphenated and contain numbers (e.g. William Gates the 3rd) or letters other than those in the English alphabet. So usually you let users type whatever they want and just deal with the spaces.