How to match 'aA1' or 'Aa1' or '1aA' with regex? - javascript

I have a text box and want to match the pattern as
[a-z]{1}[A-Z]{1}[0-9]{1}
var x=/^[a-z]{1}[A-Z]{1}[0-9]{1}$/;
if(!x.test(document.getElementById('name').value))
{
alert("enter the correct format");
return false;
}
It works only for the value : aA1
what to do if
these values can be entered randomly
like aA1, Aa1, 1aA ?

To match a set of strings in any order you can use lookahead. Something like this:
/^(?=.*a)(?=.*b)(?=.*c)[abc]{3}$/.test('cab')
The syntax (?=whatever) is a positive lookahead, meaning it checks for a match without advancing the position of matcher. So each group looks for your characters anywhere in the string. The last part [abc]{3} ensures that no other characters are present in the string, and that there are exactly three characters. If multiples are okay, use [abc]+ instead.
For a more detailed reference see http://www.regular-expressions.info/lookaround.html.

You can use the monster expression
/$([a-z][A-Z][0-9])|([A-Z][a-z][0-9])|([0-9][a-z][A-Z])|([a-z][0-9][A-Z])|([A-Z][0-9][a-z])|([0-9][A-Z][a-z])^/
but I'm not sure this is an efficient or scalable solution.

Try this
/^([a-z]{1}[A-Z]{1}[0-9]{1}|[A-Z]{1}[a-z]{1}[0-9]{1}|[0-9]{1}[a-z]{1}[A-Z]{1})$/
The First expression [a-z]{1}[A-Z]{1}[0-9]{1} deals with the pattern : aA1
The Second epression [A-Z]{1}[a-z]{1}[0-9]{1} deals with the pattern : Aa1
And the Third expression [0-9]{1}[a-z]{1}[A-Z]{1} deals with the pattern : 1aA

Related

Regex- match 3 or 6 of type

I'm writing an application that requires color manipulation, and I want to know when the user has entered a valid hex value. This includes both '#ffffff' and '#fff', but not the ones in between, like 4 or 5 Fs. My question is, can I write a regex that determines if a character is present a set amount of times or another exact amount of times?
What I tried was mutating the:
/#(\d|\w){3}{6}/
Regular expression to this:
/#(\d|\w){3|6}/
Obviously this didn't work. I realize I could write:
/(#(\d|\w){3})|(#(\d|\w){6})/
However I'm hoping for something that looks better.
The shortest I could come up with:
/#([\da-f]{3}){1,2}/i
I.e. # followed by one or two groups of three hexadecimal digits.
You can use this regex:
/#[a-f\d]{3}(?:[a-f\d]{3})?\b/i
This will allow #<3 hex-digits> or #<6 hex-digits> inputs. \b in the end is for word boundary.
RegEx Demo
I had to find a pattern for this myself today but I also needed to include the extra flag for transparency (i.e. #FFF5 / #FFFFFF55). Which made things a little more complicated as the valid combinations goes up a little.
In case it's of any use, here's what I came up with:
var inputs = [
"#12", // Invalid
"#123", // Valid
"#1234", // Valid
"#12345", // Invalid
"#123456", // Valid
"#1234567", // Invalid
"#12345678", // Valid
"#123456789" // Invalid
];
var regex = /(^\#(([\da-f]){3}){1,2}$)|(^\#(([\da-f]){4}){1,2}$)/i;
inputs.forEach((itm, ind, arr) => console.log(itm, (regex.test(itm) ? "valid" : "-")));
Which should return:
#123 valid
#1234 valid
#12345 -
#123456 valid
#1234567 -
#12345678 valid
#123456789 -

Regex to extract two digits from phone number

I am trying to take only 2 characters from my phone no.
I have used regex match ^\+55 and this will return the following example.
Phone No : +5546342543
Result : 46342543
Expected Result was only 46.
I don't want to use substring for the answer instead I want to extract that from the phone no with regex.
Can anybody help me on this.
Thank you.
The pattern you used - ^\+55 - matches a literal + in the beginning of the string and two 5s right after.
46 is the substring that appears right after the initial +55. In some languages, you can use a look-behind (see example) to match some text preceded with another.
JavaScript has no look-behind support, so, you need to resort to capturing groups.
You can use string#match or RegExp#exec to obtain that captured text marked with round brackets:
var s = '+5546342543';
if ((m=/^\+55(\d{2})/.exec(s)) !== null) {
document.write(m[1]);
}
This example handles the case when you get no match.
Just try with:
'+5546342543'.match(/^\+55(\d{2})/)[1];
This will get what you want
"+5546342543".match(/^\+55(.*)/)[1]
This solves your problem ?
phoneNumber = "+5546342543"
phone = phoneNumber.substr(3) // returns "46342543"
twoDigits = phoneNumber.substr(3,2) // returns "46"
Using the substr() method as quoted :
The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
Syntax: str.substr(start[, length])
Source : Mozilla MDN

How to javascript regex match the following?

I only want to match ones that say:
Given I string, I want something that is able to detect words that match anything with the following pattern of "TERMINATE:" + any number of random letters or numbers:
"VIRUS:XPA"
"VIRUS:IDI"
Then the function should return "true" to indicate there is only a virus.
But if the string is the following:
"ANM|SDO|FSD:SOS|VIRUS:XPA"
"ANM:SOS|SDO|FSD:SOS|VIRUS:XLS"
"VIRUS:XLS|ANM:SOS|SDO|FSD:SOS|VIRUS:XPL"
"VIRUS:XLS|ANM:SOS"
Then the function should return "false" to indicate there is no virus, or the virus is masked.
Can this be done with a single regular expression in javacsript?
You mean something like this ?
var isVirus = /^VIRUS\:\w*$/.test(str)

Matching special characters and letters in regex

I am trying to validate a string, that should contain letters numbers and special characters &-._ only. For that I tried with a regular expression.
var pattern = /[a-zA-Z0-9&_\.-]/
var qry = 'abc&*';
if(qry.match(pattern)) {
alert('valid');
}
else{
alert('invalid');
}
While using the above code, the string abc&* is valid. But my requirement is to show this invalid. ie Whenever a character other than a letter, a number or special characters &-._ comes, the string should evaluate as invalid. How can I do that with a regex?
Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
var pattern = /^[a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/
That way you can remove any individual character you want to disallow.
Also, you want to include the start and end of string placemarkers ^ and $
Update:
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
/^[\w&.\-]+$/
[\w] is the same as [a-zA-Z0-9_]
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:
/^[\w&.\-]*$/
Well, why not just add them to your existing character class?
var pattern = /[a-zA-Z0-9&._-]/
If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:
var pattern = /^[a-zA-Z0-9&._-]+$/
The added ^ and $ match the beginning and end of the string respectively.
Testing for letters, numbers or underscore can be done with \w which shortens your expression:
var pattern = /^[\w&.-]+$/
As mentioned in the comment from Nathan, if you're not using the results from .match() (it returns an array with what has been matched), it's better to use RegExp.test() which returns a simple boolean:
if (pattern.test(qry)) {
// qry is non-empty and only contains letters, numbers or special characters.
}
Update 2
In case I have misread the question, the below will check if all three separate conditions are met.
if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
// qry contains at least one letter, one number and one special character
}
Try this regex:
/^[\w&.-]+$/
Also you can use test.
if ( pattern.test( qry ) ) {
// valid
}
let pattern = /^(?=.*[0-9])(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!##$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123#"); //true as it contains all the above
I tried a bunch of these but none of them worked for all of my tests. So I found this:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$
from this source: https://www.w3resource.com/javascript/form/password-validation.php
Try this RegEx: Matching special charecters which we use in paragraphs and alphabets
Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)
.test(str) returns boolean value if matched true and not matched false
c# : ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$
Here you can match with special char:
function containsSpecialChars(str) {
const specialChars = /[`!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
return specialChars.test(str);
}
console.log(containsSpecialChars('hello!')); // 👉️ true
console.log(containsSpecialChars('abc')); // 👉️ false
console.log(containsSpecialChars('one two')); // 👉️ false

JS regular expression confusion

Firstly apologies for being a tad dim. I need to create a test to check the if the value of an input field.
I currently use /[^A-Za-z0-9 ]/.test(document.form.Serial.value) to test to see if the value of Serial is alphanumeric only.
Now, if an additional field is set, Serial must either being with 'i' or 'I', then the remaining characters must all be numbers. I had considered doing this with substrings, but it seems a bit long and unnecessary.
Any advice people can give would be very much appreciated!
If you want to test if a string begins with i or I, and then only contain numbers, you could use a regular expression such as this one :
/^[iI][0-9]+$/
Or, for a case-insensitive match :
/^i[0-9]+$/i
Basically, this will match :
Beginning of string : ^
an i
any character between 0 and 9 : [0-9]
one or more time : [0-9]+
end of string : $
You may try the code below
var test_value = false
if (document.form.Additional_Field.value) {
test_value = /^(i|I)[0-9]+/.test(document.form.Serial.value) }
else {
test_value = /[A-Za-z0-9]+/.test(document.form.Serial.value) }
it will result in test_value set to true if Serial is either alphanumeric or if Additional_Field has value true and Serial begins with i or I fallowed by any number of numbers, and test_value set to false otherwise.
Why not break the problem down. You have two valid inputs, so a pattern for syntactically checking the input would be:
/^([iI][0-9]+)|([A-Za-z0-9]+)$/
Then you have a separate, and simpler, problem of determining whether the validated input is appropriate based on the state of the other controls on the form.

Categories