Regular expression seems to treat one string as multiple substrings [duplicate] - javascript

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 7 years ago.
Why the following code returns "ZZZCamelCase"?? Doesn't such regex examine if the string starts and ends with small case a-z? As what I understand, the str variable should match such condition, so the console output should be "ZZZZZZZZZZZZ", but obviously it somehow breaks the str, and examine the substring against the regex. Why? and how can I tell the program to treat "testCamelCase" as one string?
var str = "testCamelCase";
console.log(str.replace(/^[a-z]+/, 'Z')); // ZZZCamelCase

Here you are matching one or more lower case letters. That's going to be 'test' in your string, because after that comes an uppercase 'C'. So only 'test' gets rpelaced by 'ZZZ'
console.log(str.replace(/^[a-z]+/, 'ZZZ')); // ZZZCamelCase
Use
str.replace(/[a-z]/ig, 'Z')
to get 'ZZZZZZZZZZZZ'

You are forgetting, that regex is case sensitive. This means, that [a-z] doesn't capture the whole string. [a-zA-Z] does. So does [\w] including digits from 0-9.

Related

Regex that finds all instances where a character is repeated twice adjacently? [duplicate]

This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
Closed 2 years ago.
I am trying to solve this simple HackerRank problem with regex (w/ Javascript):
https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings
To learn more about regular expressions, I want to build a regex out of my own logic so I have refused to look at the discussions, however after some turmoil in trying to make what I thought was a simple regex I have decided to ask here.
What I want to do is make a Regex that finds all pairs of consecutive alphanumeric characters, so for the string "AAAA" should match ["AA", "AA", "AA"] for the first and second As, the second and third As, and the third and fourth As, respectively. If my thinking is correct, this will count the number of adjacent repeated characters in a string.
The closest I came was
/(\w)\1{1}/g
which comes close, but seems to skip all characters it has already scanned, so it misses the "AA" comprised of the second and third As above, since it has already counted the second A in the first pair of As (I think).
Is such a regex possible?
EDIT: Thanks! Lookahead was the answer and I didn't know about that before as I am new to regex so this was good. My full function for the solution is
function alternatingCharacters(s) {
return s.match(/(\w)(?=\1)/g) != null ? s.match(/(\w)(?=\1)/g).length : 0;
}
Lookahead has to be used as it would not consume any character. In Python,
str1 = "hello he is good aaaaa"
# findall returns just capturing groups so there has to be outer capturing group too
[groups[0]+groups[1] for groups in re.findall(r'((\w)(?=\2))', str1)]
['ll', 'oo', 'aa', 'aa', 'aa', 'aa']

What is the meaning of forward slash in a JavaScript expression? [duplicate]

This question already has answers here:
Meaning of javascript text between two slashes
(3 answers)
Closed 2 years ago.
Stumbling upon a piece of JavaScript in a library I found this:
let useBlobFallback = /constructor/i.test(window.HTMLElement) || !!window.safari || !!window.WebKitPoint
but I can't find the meaning of the /constructor/i. Even searching online produces meaningless results because of the 'constructor' word and/or because the slash is also used in regular expressions. Which I believe it's not the case in this code snippet..
This is a RegExp literal. It's equivalent to new RegExp('constructor', 'i').test(window.HTMLElement).
Have a look at this maybe?
Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern /abc/ matches character combinations in strings only when the exact sequence "abc" occurs (all characters together and in that order). Such a match would succeed in the strings "Hi, do you know your abc's?" and "The latest airplane designs evolved from slabcraft." In both cases the match is with the substring "abc". There is no match in the string "Grab crab" because while it contains the substring "ab c", it does not contain the exact substring "abc".

Regex allows spaces [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 5 years ago.
For the following regex expression:
var regex = new RegExp("^(www\\.)?[0-9A-Za-z-\\.#:%_\+~#=]+(\\.[a-zA-Z]{2,})+(/.*)?(\\?.*)?");
I don't understand why the string "www.goo gle.com" passes the regex test. When I did this:
var regex = new RegExp("^(www\\.)?[0-9A-Za-z-\\.#:%_\+~#=]+(\\.[a-zA-Z]{2,})+(/.*)?(\\?.*)?$");
i.e. adding $ in the end of the regex string prevents the above string passing, which is what I would want.
I tried finding a "simulator" online to help me figure out how the regex is matching but couldn't find much help.
www.goo gle.com passes the test since, www. is matched by [0-9A-Za-z-\\.#:%_\+~#=]+ and
goo is matched by (\.[a-zA-Z]{2,})+. In contrast, (www\\.)?, and the last two groups are optional, so the regex is satisfied even if they are not matched, hence there's no need to further match gle.com.
By adding $, the regex no longer matches, since the space is not matched by any of the subexpressions.

how to write a regular expression that ONLY accepts strings [duplicate]

This question already has answers here:
Regular Expression to match only alphabetic characters
(5 answers)
Closed 7 years ago.
I am trying to understand regular expressions, i find it really confusing to understand it. I need to know how to write a regular expression that ONLY matches strings, NO NUMBERS, NO SPECIAL CHARACTERS, just letters from A - Z. I have to say that I tried using \[a-z]\ but it didn't work as i wanted. These are some of the results that I want:
pe<.?ter -----> should return false
ale8 ---------> should return false
?ramon -------> should return false
tho<>?mass----> should return false
peter -----> should return true
alex ------> should return true
ramon -----> should return true
thomas ----> should return true
This should work for you:
var re = /^[a-z]+$/i;
See here
Your regex returns true if it find ONE letter from a to z, only lowercase, in your string.
To make what you want, use /^[a-zA-Z]+$/ or /^[a-z]+$/i.
^ make that your regex start from the begining of the string.
[a-zA-Z] make the regex to find one letter, lowercase OR uppercase (note that you could use instead the i modifier which make the search case insensitive).
+ make the regex to search for one or more times the previous element.
$ make sure that your regex end at the end of the string.

Perfect solution to validate a password [duplicate]

This question already has answers here:
regular expression for password with few rules
(3 answers)
Closed 8 years ago.
I took an online JavaScript test where the 3rd problem was as follows:
Complete the checkPassword function, which should check if the password parameter adheres to the following rules:
Must be longer than 6 characters.
Allowed characters are lower or uppercase Latin alphabetic characters (a-z), numbers (0-9), and special characters +, $, #, \, / only.
Must not have 3 or more consecutive numbers (e.g. "pass12p" is fine,
but "pass125p" is not, because it contains "125")
>
My solution was as follows:
function checkPassword(password) {
return /^[a-zA-Z0-9\+\$\\\/#]{6,}$/.test(password) && !/[0-9]{3,}/.test(password);
}
This solution gave me the correct outputs for the given inputs.
But the ultimate test result told that the solution is just 75% correct sadly.
I think the perfect answer is expected to be a solution just with a single regular expression. Is there anyone who can give me a single regular expression that gives the same result? I am not so good at regular expression so please advise.
I appreciate your help in advance.
Just use a negative lookahead at the start.
^(?!.*?\d{3})[a-zA-Z0-9\+\$\\\/#]{6,}$
(?!.*?\d{3}) at the start asserts that the match won't contain atleast three consecutive digits. Then the regex engine tries to match the pattern [a-zA-Z0-9\+\$\\\/#] against the input string 6 or more times only if this condition is satisfied.
DEMO
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{6,}$
For consecutive number check
public boolean isValid(final String userName,final String password) {
for(int i=0;(i+2)<userName.length();i++) if(password.indexof(userName.substring(i,i+2))!=-1) return false; return true;
}

Categories