The string can be a number or a set of numbers, or two groups of numbers separated with "-", but total count of all characters mustn't be more than 6.
Example of valid strings
5
55-33
4444-1
1-4444
666666
Example of invalid strings
-3
6666-
5555-6666
My regex
/^\d+(-?\d+)?$/
But this regex interprets 5555-6666 as a valid string, though its length is more than 6 characters.
I tried following
/^(\d+(-?\d+)?){1,6}$/
but, than I recognized that it interpret enclosed charset as one group, which it expects from 1 to 6.
So how to control total number of chars just with a regexp and requirements described above?
Mehotd 1 :-
Easiest thing you can do it test the length before regex ( i will prefer using this method which checks length and then use regex )
str.length < 7 && /^\d+(-?\d+)?$/.test(str)
Method 2 :-
You can use positive lookahead
^(?=.{0,6}$)\d+(-?\d+)?$
Regex Demo
You can use a positive lookahead pattern to ensure that there can be a maximum of 6 characters:
^(?=.{1,6}$)\d+(?:-\d+)?$
Demo: https://regex101.com/r/kAxuZp/1
Or you can a negative lookahead pattern to ensure that the string does not start with a dash, and another negative lookahead pattern to ensure that the string does not contain two dashes:
^(?!-)(?!.*-.*-)[\d-]{0,5}\d$
Demo: https://regex101.com/r/kAxuZp/3
One option would be to use your current regex pattern and also check the length of the input with dash removed:
var input = "4444-1";
if (/^\d+(-?\d+)?$/.test(input) && input.replace("-", "").length <= 6) {
console.log("MATCH");
}
else {
console.log("NO MATCH");
}
Note that checking the length of the input is only really meaningful after the dash has been removed, because it is only then that we can assert the total number of actual digits.
Related
I'm trying to hide/replace with * the 6 middle characters of a number, but I'm not getting the desired result.
Input:
54998524154
Expected output:
54*****154
What I tried:
const phone = "54998524154"
phone.replace(/(?<=^[0-9]{2})([0-9]{6})/g, '*')
It returns
54*154
I also tried replaceAll, but it returns the same result.
Edit: I'd like to achieve it using only one * like:
Replace phone numbers with asterisks pattern by Regex
Regex replace phone numbers with asterisks pattern
Is this what you had in mind? It matches the 3rd through 8th digit successively, replacing each single digit with a single asterisk.
/(?<=^\d{2,7}?)\d/g
It takes advantage of Javascript's ability to specify variable length lookbehinds.
Here it is on Regex101, with your single example:
EDIT
Based on OP's comments, it seems like there may be punctuation between the digits that should be preserved. This approach can be easily extended to ignore non-digits (\D in regex) by adding an optional number of them before and after each digit. Like this:
(?<=^\D*(\d\D*){2,7}?)\d
This will turn (123) 456-7890 into (12*) ***-**90, preserving all punctuation.
If the input is always going to be 11 chars/digits, you could do something like
phone.replace(/(^\d{2})(\d{6})(\d{3}$)/g, "$1******$3");
Explanation:
3 capture groups:
(^\d{2}) - from the beginning of the string, select 2 digits
(\d{6}) - then select 6 digits
(\d{3}$) - Select last 3 digits
Replace pattern:
"$1******$3" - First capture-group, then 6 asterisks, then 3rd capture-group.
You can do this with the below regex.
console.log("54998524154".replace(/(\d{2})\d{6}/,"$1******"))
In fact, you can do it without regex as well.
var numStr = '54998524154';
console.log(numStr.replace(numStr.substring(2,8), "******"));
Without lookarounds, you might also using split check if the characters are digits and then change single digits to * between 2 and 9 characters:
const toAsterix = s => {
let cnt = 0;
return s.split('').map(v => {
const isDigit = /^[0-9]$/.test(v);
if (isDigit) cnt++;
return cnt > 2 && cnt < 9 && isDigit ? "*" : v
}).join('');
}
[
"54998524154",
"(123) 456-7890"
].forEach(s => console.log(toAsterix(s)))
I have to validate string field which start with A-za-z and can contain 0-9_. I have to set limit min 1 char and max 10 char.
Exp=/^([a-zA-Z]) +([0-9._]*)/;
Try this regex:
/^[a-zA-Z][0-9_]{0,9}$/
See demo on regex101.com.
I have to validate string field which start with A-za-z and can contain 0-9_.
I guess A-za-z is a typo, you meant A-Za-z. That is easy, we use ^ for the string start and [A-Za-z] character class for the letter.
I have to set limit min 1 char and max 10 char.
That means, we already have the "min 1 char" requirement fulfilled at Step 1 (one letter at the start). Now, we may have letters, digits, or an underscore, 0 to 9 occurrences - that is, we need to use {0,9} limiting quantifier - up to the end of string (that is, $). A shorthand pattern in JS regex for letters, digits, and underscore is \w.
Use
/^[a-zA-Z]\w{0,9}$/
var re = /^[a-zA-Z]\w{0,9}$/;
var str = 'a123456789';
if (re.test(str)) {
console.log("VALID!")
} else {
console.log("INVALID!")
}
function isValid(string){
if (string.length < 1 || string.length > 10)
return false;
return /^[a-zA-Z][0-9_]*$/.test(string);
}
console.assert(isValid("A"));
console.assert(isValid("a12345"));
console.assert(!isValid(""));
console.assert(!isValid("x123456787212134567"));
console.assert(!isValid("abcdef"));
console.assert(!isValid("012345"));
Don't try to check string length with regex, in most of the cases it is slow and burdensome.
I am using this pattern:
^\w+( \w+)*$
to validate that a string is alphanumeric and may contain spaces. I can't figure out how to set a min and max though. I'd like something like this:
^(\w+( \w+)*){1, 50}$
but it's not working. What is the correct syntax?
EDIT: Sample input:
3this String is fine12
If the length of the entire string is greater than 50 though, it should not match.
If you want to limit the input string length you can use a restrictive positive lookahead at the start:
/^(?=.{1,50}$)\w+(?: \w+)*$/
The input string length can range from 1 to 50 characters.
See regex demo
Explanation:
^ - start of string
(?=.{1,50}$) - the positive lookahead that requires the string to have at least 1 character and up to 50 (note the $ is very important here)
\w+ - 1 or more word characters
(?: \w+)* - zero or more sequences of a space followed by 1 or more word characters
$ - end of string
I was trying to write regex for above mentioned rule I tried this way but its not working
"(?=^([0-9]|-){8,20}$)^[0-9]+[/-/][0-9]+$"
so, you could make the problem much simpler by creating a regex that tests that a string consists of 8 to 20 characters (numeric, space or hyphen), where the hyphen cannot be the first or the last character:
/^[\d\s][\d\s\-]{6,18}[\d\s]$/
and then test that the string contains a single hypen:
/^[^\-]*\-[^\-]*$/
and then that it contains a space:
/\s/
I appreciate this is a slightly different answer than what you were asking for, but thought it might help
I don't think it's possible to check the length AND the format of the string with only one regex. However, you could achieve this with 2 steps, for example:
var formatRegex = /^\d+(?:\d|\s)*-(?:\d|\s)+$/;
var myText = '111-111 11 111';
if (formatRegex.test(myText)) {
if (myText.length >= 8 && myText.length <= 20) {
console.log('ok');
}
}
^[0-9](?:([0-9]{5,17}-)|(?=[0-9]*[-][0-9]*$)[0-9-]{6,18})[0-9]$
this regex is working
explanation:
it will check string starting with [0-9] and ending with [0-9]
now for remaining string of length we can have this pattern (?:[0-9]{5,17}|(?=[0-9][-][0-9]$)[0-9-]{6,18})
where ?:([0-9]{5,17}-) will check presence of 5 to 17 numbers and one - in string
demo:
https://regex101.com/r/eO3jK8/1
How to validate a password allows at least 4 digits and 1 character without special character using regular expression?
Password Valid Format: 1234a or 6778B or 67A89 (Without Special Characters Like #$%^&*/)
Maximum Password Length : 5 Characters Long
Can any one help me how to do this?.
Thanks.
The pattern you want
any number of numbers
then a letter
any number of numbers
additional restriction as in all should not be longer than 5 chars
The patter could be this: (using positive lookahead to check the numbers-letter-numbers combination then checking for 5 characters to check length)
/^(?=[0-9]*[a-zA-Z][0-9]*$).{5}$/
This regex should work:
^(?=(.*?[0-9]){4})(?=.*?[a-zA-Z])[0-9A-Za-z]{5}$
Since we are only allowing [0-9A-Za-z]{5} symbols in password there is no need to check for special characters here.
Online Demo: http://regex101.com/r/mB6sS5
Explanation:
(?=(.*?[0-9]){4}) - Lookahead to check for presence of at least 4 numbers
(?=.*?[a-zA-Z]) - Lookahead to check for presence at least 1 letter
[0-9A-Za-z]{5} Only allows symbols in character class with max length=5
^[0-9]{4}[A-Za-z]{1}$
This will let you enter four numbers (0-9) and 1 letter (a-z and A-Z) example 1234a.... hope this is the answer you were looking for.
Below is the javascript code for doing the checking you need
var regex =^(?=(.*?[0-9]){4})(?=.*?[a-zA-Z])[0-9A-Za-z]{5}$;
var input = "1234B";
if(regex.test(input)) {
alert(matches[match]);
} else
{
alert("No matches found!");
}