Javascript RegEx not returning false as expected - javascript

Not a big user of RegEx - never really understood them! However, I feel the best way to check input for a username field would be with one that only allows Letters (upper or lower), numbers and the _ character, and must start with a letter as per the site policy. The My RegEx and code is as such:
var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));
Despite trying with various combinations, everything is returning "true".
Can anyone help?

Your regex is saying "does theUsername contain a letter, digit, or end with underscore".
Try this instead:
var theCheck = /^[a-z]([a-z_\d]*)$/i; // the "i" is "ignore case"
This says "theUsername starts with a letter and only contains letters, digits, or underscores".
Note: I don't think you need the "g" here, that means "all matches". We just want to test the whole string.

How about something like this:
^([a-zA-Z][a-zA-Z0-9_]{3,})$
To explain the entire pattern:
^ = Makes sure that the first pattern in brackets is at the beginning
() = puts the entire pattern in a group in case you need to pull it out and not just validate
a-zA-Z0-9_ = matches your character allowances
$ = Makes sure that this must be the entire line
{3,} = Makes sure there are a minimum of 3 characters.
You can add a number after the comma for a character limit max
You could also use a +, which would merely enforce at least one character match the second pattern. A * would not enforce any lengths

Use this as your regex:
^[A-Za-z][a-zA-Z0-9_]*$

Related

Name Validation Using Regular Expressions

I'm using a regular expression in my code, to validate the name and send the form, I just need some help by using it.
The Name should start by a capital letter and could be from 2-3 words, and could be separated by an apostrophe, space or a dash such as :
Victor Hugo
Jeanne D'arc
Jean-Marc Ayrault
I tried starting it by a capital, using /^[A-z][a-z]/
But i don't know how to continue it to validate spaces and dashes and apostrophes.
/^[A-z][a-z]/
I don't know how to continue it, thank you for your help.
You can use this regex,
\b[A-Z][a-z]*(?:'[a-z]+)?(?:[ -][A-Z][a-z]*(?:'[a-z]+)?)*\b
Explanation:
\b[A-Z][a-z]* - Starts matching a word boundary and uppercase letter followed by zero or more lowercase letters
(?:'[a-z]+)? - Optionally followed by ' and some lowercase letters. If you want to repeat this more than once, change ? to * like if you really want to support names like D'arcd'arc which I doubt if you wanted which is why I kept it with ?
(?:[ -] - Starts another non-grouping pattern and starts matching either with a space or hyphen
[A-Z][a-z]*(?:'[a-z]+)?)* - Further matches the same structure as in start of regex and zero or more times.
\b - Stops after seeing a word boundary
Demo
You could try the code below:
I'd suggest playing about with https://regexr.com/ for this purpose, it's very handy!
I've added a isValidNameStrict which only accepts a limited number of characters in the name.
Modify the [a-z'] group as you see fit to add extra characters.
function isValidNameStrict(name) {
let regEx = /^([A-Z][a-z']*[\-\s]?){2,}$/;
return regEx.test(name);
}
function isValidName(name) {
let regEx = /^(?:[A-Z][^\s]*\s?){2}$/;
return regEx.test(name);
}
function testName(name) {
console.log(`'${name}' is ${isValidNameStrict(name) ? "valid": "not valid"}`);
}
testName("Victor Hugo");
testName("Jeanne D'arc");
testName("Jean-Marc Ayrault");
testName("The Rock");
testName("Victor hugo");
testName("");
testName("Ozymandias");

How to extract a string that conforms to a regex?

Say I have a RegEx like the following:
^[a-zA-Z]\w{12}$
And I have the following string:
%7AgTy!5hG^vxWa2#AgW
I would like to "pull" out of that string something that conforms to that regex. In this example we would get the following:
AgTy5hGvxWa2A
Reason: it starts with A because the regex says the first letter must be [a-zA-Z] (so it skips the first 2 characters), and then it pulls successive \ws out until it reaches 12 characters.
Is this sort of thing possible?
Edit: My apologies for being unclear. I'm not looking for a new regular expression that will give the proper output. Rather, I'm looking for a way to use the existing RegEx to extract the proper output. In my program these regular expressions are entered by hand by the user to extract a password from a long base256 hash such that it will conform to these existing password requirement regexes.
Instead of trying to match what you want and reconstructing the string, replace everything you don't want with nothing. This gives the impression that you're extracting what you need, but, in fact, it's doing the opposite; gets rid of everything you don't want to extract. I also dropped $ from the end of your original pattern otherwise it'll never match the string you present in your question.
See regex in use here
^[^a-z]+|\W+
^ Assert position at the start of the line
[^a-z]+ Matches any character that is not in the range a-z one or more times. Since the i flag is specified, this also matches A-Z
\W+ Match any non-word character one or more times
const regex = /^[^a-z]+|\W+/gi
const a = [
`%7AgTy!5hG^vxWa2#AgW`,
`%7AgTy!5hG^vxWa2#`
]
a.forEach(function(s) {
var clean = s.replace(regex, '')
var match = clean.match(/^[a-z]\w{12}/i)
console.log(match)
})

How can I create a regular expression that accepts at least one lowercase and one digit?

This expression must adhere to specific rules:
1.- Between 2 and 8 characters total.
2.- Start with uppercase.
3.- Contain both lowercase and digits.
The first and second should be easy, but I can't get the third one to work.
This is the expression I came up with
([A-Z]+[A-Za-z0-9]*){2,8}
But it returns incorrect responses. Regular expressions are far from my forte, and this is the first time I had to use them outside of class.
This is my code, if it helps
var expresion = /([A-Z]+[A-Za-z0-9]*){2,8}/;
var re = new RegExp(expresion);
var t = $('#code').val();
if (re.test(t)) {
console.log(t+' works');
} else {
console.log(t+' not working');
}
This should fit your literal requirements (however, as comments state, they don't really make sense):
^(?=.{2,8}$)(?=.*[0-9])(?=.*[a-z])[A-Z][a-zA-Z0-9]*$
First, you need to anchor your match with ^ (start of string) and $; otherwise you can just be picking up a matching substring, which will mess up your requirements.
Second, we use lookahead to validate several individual points: the string contains between 2 and 8 characters before it ends, the string contains a digit.
Third, we use the character classes to validate that it starts with an uppercase, and continues with a mix of uppercase, lowercase and digits.
EDIT: Forgot the lowercase requirement, thanks nnnnnn. And you are right, your version is better.
Use look aheads that comport to each condition:
/^(?=[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{2,8}$)(.*)/m
Demo
(As stated in comments, your target pattern is a minimum of 3 characters with the other conditions...)

JavaScript and regular expressions: get the number of parenthesized subpattern

I have to get the number of parenthesized substring matches in a regular expression:
var reg=/([A-Z]+?)(?:[a-z]*)(?:\([1-3]|[7-9]\))*([1-9]+)/g,
nbr=0;
//Some code
alert(nbr); //2
In the above example, the total is 2: only the first and the last couple of parentheses will create grouping matches.
How to know this number for any regular expressions?
My first idea was to check the value of RegExp.$1 to RegExp.$9, but even if there are no corresponding parenthseses, these values are not null, but empty string...
I've also seen the RegExp.lastMatch property, but this one represents only the value of the last matched characters, not the corresponding number.
So, I've tried to build another regular expression to scan any RegExp and count this number, but it's quite difficult...
Do you have a better solution to do that?
Thanks in advance!
Javascripts RegExp.match() method returns an Array of matches. You might just want to check the length of that result array.
var mystr = "Hello 42 world. This 11 is a string 105 with some 2 numbers 55";
var res = mystr.match(/\d+/g);
console.log( res.length );
Well, judging from the code snippet we can assume that the input pattern is always a valid regular expression, because otherwise it would fail before the some code partm right? That makes the task much easier!
Because We just need to count how many starting capturing parentheses there are!
var reg = /([A-Z]+?)(?:[a-z]*)(?:\([1-3]|[7-9]\))*([1-9]+)/g;
var nbr = (' '+reg.source).match(/[^\\](\\\\)*(?=\([^?])/g);
nbr = nbr ? nbr.length : 0;
alert(nbr); // 2
And here is a breakdown:
[^\\] Make sure we don't start the match with an escaping slash.
(\\\\)* And we can have any number of escaped slash before the starting parenthes.
(?= Look ahead. More on this later.
\( The starting parenthes we are looking for.
[^?] Make sure it is not followed by a question mark - which means it is capturing.
) End of look ahead
Why match with look ahead? To check that the parenthes is not an escaped entity, we need to capture what goes before it. No big deal here. We know JS doens't have look behind.
Problem is, if there are two starting parentheses sticking together, then once we capture the first parenthes the second parenthes would have nothing to back it up - its back has already been captured!
So to make sure a parenthes can be the starting base of the next one, we need to exclude it from the match.
And the space added to the source? It is there to be the back of the first character, in case it is a starting parenthes.

New to Regular Expressions need help

I need a form with one button and window for input
that will check an array, via a regular expression.
And will find a exact match of letters + numbers. Example wxyz [some space btw] 0960000
or a mix of numbers and letters [some space btw] + numbers 01xg [some space btw] 0960000
The array has four objects for now.
Once found i need a function the will open a new page or window when match is found .
Thanks you for your help.
Michael
To answer the Javascript part, here's one way to "grep" through the array to find matching elements:
var matches = [];
var re = /whatever/;
foo.forEach(
function(el) {
if( re.exec(el) )
matches.push(el);
}
);
To attempt to answer the regular expression part: I don't know what "exact match" means to you, and I'm assuming "some space" belongs only in between the other terms, and I'm assuming letters means the English alphabet from 'a' to 'z' in lower and upper case and the digits should be 0-9 (otherwise, other language characters might be matched).
The first pattern would be /[a-zA-Z0-9]+\s*0960000/. Change "\s*" to "\s+" if there is at least one space, instead of zero or more space characters. Change "\s" to " " if matching the tab character (and some lesser-used space chars) is not desirable.
For the second pattern, I don't know what "numbers 01xg" means, but if it means numbers followed by that string, then the pattern would be /[a-zA-Z0-9]+\s*[0-9]+\s*01xg\s*0960000/. The same caveats apply as above.
Additionally, this will match a partial string. If the string much be matched in entirety (if nothing in the string must exist except that which is matched), add "^" to the beginning of the pattern to anchor it to the beginning of the string, and "$" at the end to anchor it to the end of the string. For example, /[a-zA-Z0-9]+\s*0960000/ matches "foo_bar 5 0960000", but /^[a-zA-Z0-9]+\s*0960000$/ does not.
For more on regular expressions in Javascript, take a look at developer.mozilla.org's article on the RegExp object (the link takes you to JS version 1.5 reference, which should apply to all JS-capable browsers).
(edited to add): To match either situation, since they have overlapping parts, you could use the following pattern: /[a-zA-Z0-9]+(?:\s*[0-9]+\s*01xg)?\s*0960000/. The question mark says to match the part that differs -- in a non-matching group (?:foo) -- once or zero times. (?:foo)? and (?:foo|) do the same thing in this case, but I'm not sure whether there is a performance difference; I would recommend to use the one that makes the most sense to you, so you can read it later.

Categories

Resources