I can't seem to figure out the regular expression - javascript

I have the following code. I am trying to have the regular express test the phone number for validation. With the current argument the function should return positive, but it doesn't and I can't figure out why.
function telephoneCheck(str) {
let reg = /^[\d]{0,1}[\w]{0,1}[(]{0,1}[\d]{3}[-)\w]{0,2}[\d]{3}[-\w]{0,1}[\d]/;
return reg.test(str);
}
console.log("function: " + telephoneCheck("1 (555) 555-5555"));
Can anyone see what I am missing?

First, replace all the \w (Matches any letter, digit or underscore) with \s (Matches any space, tab or newline character). I believe you don't won't letter in phone number.
Second, you need to add a quantifier {0,4} to the end of your Regex, just like you already did in other positions of the Regex.
So the final Regex will be ^[\d]{0,1}[\s]{0,1}[(]{0,1}[\d]{3}[-)\s]{0,2}[\d]{3}[-\s]{0,1}[\d]{0,4}

Because your regex is nonsense.
No need for [] for single group ([\d]{0,1} can be just \d?
\w does not match spaces, just [a-z0-9] in general case
You match starting ( but ending ) can be followed by - or any \w
function telephoneCheck(str) {
let reg = /^\d?\s?\(?[\d-]+\)?\s?\d+/;
return reg.test(str);
}
console.log("function: " + telephoneCheck("1 (555) 555-5555"));

You need to replace \w with \s for whitespace
You need to escape parenthesis \( and \)
You need to change [-)\w]{0,2} to [-\)]{0,1}[\s]{0,1} unless you want the unorthodox 1 (555)-555-5555 to be true.
The final [\d] should be [\d]{4} since you want exactly 4 digits at the end.
You can replace the {0,1} with ? when evaluating a single character that is optional.
You don't need brackets around single characters.
Here's the resulting code:
function telephoneCheck(str) {
let reg = /^\d?\s?\(?\d{3}[-\)]{0,1}\s?\d{3}[-\s]?\d{4}/;
return reg.test(str);
}
console.log(telephoneCheck("1 (555)555-5555")); // true
console.log(telephoneCheck("1 (555)5555555")); // true
console.log(telephoneCheck("(555)555-5555")); //true
console.log(telephoneCheck("15555555555")); //true
console.log(telephoneCheck("1 (555)555- 5555")); // false
console.log(telephoneCheck("1 (555)-555-5555")); // false

Related

Pass the regex test if there is only one space in the string

I am trying to get lines where there is a single space. I am currently doing it a different way because I still can't find a regex for it:
const line= "a b c";
/ {1}/.test(line)
Expected: false
Gets: true
I think this isn't syntactically good but am open to suggestions:
line.match(/ /g).length == 1
What should I look into?
Use the following regex test:
/^\S* (?=\S*)$/.test(line)
^\S* - starts with optional non-spaces chars
(?=\S*)$ - positive lookahead, ensures that space is followed by any number of non-space chars (if occur) to the end of the string
The regular expression /^[^\s]\s[^\s]$/ matches a string that contains only a single whitespace character.
here is the code example:
const regex = /^[^\s]*\s[^\s]*$/;
console.log(regex.test("ab c")); // true
console.log(regex.test("a b c")); // false
Matching a string without newlines containing a single space
^\S* \S*$
Explanation
^ Start of string
\S* Match optional non whitespace chars
Match a single space
\S* Match optional non whitespace chars
$ End of string
See a regex101 demo.
const regex = /^\S* \S*$/;
[
"a b c",
"",
" ",
" ",
"a ",
"a b"
].forEach(s =>
console.log(`'${s}' --> ${regex.test(s)}`)
);
The question is not clear for me.
The {1} on the first regex does not have any effect this way but it makes me think that you do not want to accept multiple consecutive spaces. The second regex is just fine if you are interested only in the lines that contain exactly one space.
What exactly do you need?
Do you want the line to contain exactly one space?
Or multiple spaces are allowed, just to not be consecutive?
The following code snippet shows solutions for both questions:
function test(input) {
console.log({
input,
exactlyOne: (input.match(/ /g) ?? []).length === 1,
noConsecutive1: / {2}/.test(input) === false,
noConsecutive2: input.includes(' ') === false,
});
}
// no consecutive spaces
test('a b c');
test('a b');
test('a');
test('a ');
test(' ');
test('');
// consecutive spaces; they all should report "exactlyOne: false, noConsecutive: false"
test('a b c');
test('a b');
test('aa ');
test(' ');
The second search can be done without regexps. I cannot tell if it runs faster; for large inputs I think that the regexp is faster but I didn't check.
if (input.includes(' ')) {
console.log('two consecutive spaces found in the input');
}
I added it to the code snippet above.
How about:
^[^\s]*\s[^\s]*$
Explanation:
Start: ^
Any number of non-spaces: [^\s]*
A single space \s
Any number of non-spaces (again): [^\s]*
End: $

use regex to replace spaces that occur with a value depending on how many spaces found

I want to use a regex that looks for spaces with a minimum length of 2 in a row, and replaces the occurrence with another value for each occurrence of the space found.
For example:
I love to eat cake
There are 3 spaces after love and 4 spaces after eat. I want my regex to replace occurrences of a space more than 1, and to replace it with a value for each occurrence found.
The output I am trying to go for:
I love---to eat----cake
I tried something like
myStr.replace(/ +{2,}/g, '-')
You may use this code with a lookahead and a lookbehind:
const s = 'I love to eat cake'
var r = s.replace(/ (?= )|(?<= ) /g, '-');
console.log(r);
//=> 'I love---to eat----cake'
RegEx Details:
(?= ): Match a space only if that is followed by a space
|: OR
(?<= ) : Match a space only if that is preceded by a space
You can match two or more whitespaces and replace with the same amount of hyphens:
const s = 'I love to eat cake'
console.log(s.replace(/\s{2,}/g, (x) => '-'.repeat(x.length)) )
The same approach can be used in Python (since you asked), re.sub(r'\s{2,}', lambda x: '-' * len(x.group()), s), see the Python demo.
Also, you may replace any whitespace that is followed with a whitespace char or is preceded with whitespace using
const s = 'I love to eat cake'
console.log(s.replace(/\s(?=\s|(?<=\s.))/gs, '-') )
console.log(s.replace(/\s(?=\s|(?<=\s\s))/g, '-') )
See this regex demo. Here, s flag makes . match any char. g makes the regex replace all occurrences. Also,
\s - matches any whitespace
(?=\s|(?<=\s.)) - a positive lookahead that matches a location that is immediately followed with a whitespace char (\s), or (|) if it is immediately preceded with a whitespace and any one char (which is the matched whitespace). If you use (?<=\s\s) version, there is no need of s flag, \s\s just makes sure the whitespace before the matched whitespace is checked.

Regex - I want my string to end with 2 special character

I've been trying to make a regex that ends with 2 special characters, but I couldnt find solution. Here is what i tried, but it seems like it is not working.
/.[!##$%^&*]{2}+$/;
Thanks in advance.
Try this regex:
^.*[!##$%^&*]{2}$
Demo
const regex = /^.*[!##$%^&*]{2}$/;
const str = `abc##\$`;
let m;
if(str.match(regex)) {
console.log("matched");
}
else
console.log("not matched");
The /.[!##$%^&*]{2}+$/ regex matches
. - any character but a line break char
[!##$%^&*]{2}+ - in PCRE/Boost/Java/Oniguruma and other regex engines supporting possessive quantifiers, it matches exactly 2 cars from the defined set, but in JS, it causes a "Nothing to repeat" error
$ - end of string.
To match any string ending with 2 occurrences of the chars from your defined set, you need to remove the . and + and use
console.log(/[!##$%^&*]{2}$/.test("##"))
Or, if these 2 chars cannot be preceded by a 3rd one:
console.log(/(?:^|[^!##$%^&*])[!##$%^&*]{2}$/.test("##"))
// ^^^^^^^^^^^^^^^^^
The (?:^|[^!##$%^&*]) non-capturing group matches start of string (^) or (|) any char other than !, #, #, $, %, ^, &, * ([^!##$%^&*])

Regular Expression for alphabets, numbers and symbols

I am looking for a regex for allowing
Alphabets case insensitive [a-zA-Z]
hyphen and underscore [-_]
forward and backward slashes [/\\\\]
numbers [0-9]
Hence
var regex = new RegExp('^[a-zA-Z-_][/\\\\]*$');
regex.test('ABC/90-1_AB');
does not work.
Your current regexp (/^[a-zA-Z-_][/\\\\]*$/) is looking for a string that start with a letter, - or _ who are then followed by 0 or more / or \ that end the string.
Put it inside 1 bracket :
'^[-_/0-9a-zA-Z\\\\]*$'
Try:
var regex = new RegExp('[\w\\/-]','i'); // \w matches alphanumeric characters and underscore
regex.test('ABC/90-1_AB'); // returns true
JSFIDDLE
Since you aren't willing to have complex RegExp why making it difficult, when you can just match your needs with explicitly required symbols

RegExp issues - character limit and whitespace ignoring

I need to validate a string that can have any number of characters, a comma, and then 2 characters. I'm having some issues. Here's what I have:
var str="ab,cdf";
var patt1=new RegExp("[A-z]{2,}[,][A-z]{2}");
if(patt1.test(str)) {
alert("true");
}
else {
alert("false");
}
I would expect this to return false, as I have the {2} limit on characters after the comma and this string has three characters. When I run the fiddle, though, it returns true. My (admittedly limited) understanding of RegExp indicates that {2,} is at least 2, and {2} is exactly two, so I'm not sure why three characters after the comma are still returning true.
I also need to be able to ignore a possible whitespace between the comma and the remaining two characters. (In other words, I want it to return true if they have 2+ characters before the comma and two after it - the two after it not including any whitespace that the user may have entered.)
So all of these should return true:
var str = "ab, cd";
var str = "abc, cd";
var str = "ab,cd";
var str = "abc,dc";
I've tried adding the \S indicator after the comma like this:
var patt1=new RegExp("[A-z]{2,}[,]\S[A-z]{2}");
But then the string returns false all the time, even when I have it set to ab, cd, which should return true.
What am I missing?
{2,} is at least 2, and {2} is exactly two, so I'm not sure why three characters after the comma are still returning true.
That's correct. What you forgot is to anchor your expression to string start and end - otherwise it returns true when it occurs somewhere in the string.
not including any whitespace: I've tried adding the \S indicator after the comma
That's the exact opposite. \s matches whitespace characters, \S matches all non-whitespace characters. Also, you probably want some optional repetition of the whitespace, instead of requiring exact one.
[A-z]
Notice that this character range also includes the characters between Z and a, namely []^_`. You will probably want [A-Za-z] instead, or use [a-z] and make your regex case-insensitive.
Combined, this is what your regex should look like (using a regular expression literal instead of the RegExp constructor with a string literal):
var patt1 = /^[a-z]{2,},\s*[a-z]{2}$/i;
You are missing ^,$.Also the range should be [a-zA-Z] not [A-z]
Your regex should be
^[a-zA-Z]{2,}[,]\s*[A-Za-z]{2}$
^ would match string from the beginning...
$ would match string till end.
Without $,^ it would match anywhere in between the string
\s* would match 0 to many space..

Categories

Resources