I'm trying to build a regex which allows the following characters:
A-Z
a-z
1234567890
!##$%&*()_-+={[}]|\:;"'<,>.?/~`
All other characters are invalid. This is the regex I built, but it is not working as I expect it to. I expect the .test() to return false when an invalid character is present:
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*/g
return regex.test(string);
}
In this case, the test is always returning "true", even when "^" is present in the string.
Your regex only checks that at least one of the allowed characters is present. Add start and end anchors to your regex - /^...$/
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g
return regex.test(string);
}
... another approach, is instead of checking all characters are good, to look for a bad character, which is more efficient as you can stop looking as soon as you find one...
// return true if string does not (`!`) match a character that is not (`^`) in the set...
return !/[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/.test()
Instead of searching allowed characters search forbidden ones.
var string = 'abcd^wyd';
function regTest (string) {//[^ == not
var regex = /[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/g
return !regex.test(string);//false if found
}
console.log(regTest(string));
The regex, as you've written is checking for the existence of the characters in the input string, regardless of where it appears.
Instead you need to anchor your regex so that it checks the entire string.
By adding ^ and $, you are instructing your regex to match only the allowed characters for the entire string, rather than any subsection.
function isValidPassword (pwd) {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g\;
return regex.test(pwd);
}
alert(isValidPassword('abcd^wyd'));
Your regexp is matching the first part of o=your string i.e. "abcd" so it is true . You need to anchor it to the start (using ^ at the beginning) and the end of the string (using $ at the end) so your regexp should look like:
^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]$
That way it will need to match the entire string.
You can visualize it in the following link:
regexper_diagram
This regex will work.
var str = 'eefdooasdc23432423!##$%&*()_-+={[}]|:;"\'<,>.?/~\`';
var reg = /.|\d|!|#|#|\$|%|&|\*|\(|\)|_|-|\+|=|{|\[|}|]|\||:|;|"|'|<|,|>|\.|\?|\/|~|`/gi;
// test it.
reg.test(str); //true
I use this site to test my regex.
Regex 101
Related
I am currently replacing all non-letter characters using
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]/g, '');
The problem is that I do not know which special character will appear (that needs removing). However I do need to be able to access the removed special character after I've run some code with the word without the special character.
Example inputs:
"test".
(temporary)
foo,
Desired output:
['"','test','"',"."]
['(','temporary',')']
['foo',',']
How could this be achieved in javascript?
Edit: To get both valid and invalid characters, change the regular expression
Quick solution is to define an array to collect the matches.
Then pass in a function into your replace() call
var matches = [];
var matcher = function(match, offset, string) {
matches.push(match);
return '';
}
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]|[\w\s!?]+/g, matcher);
console.log("Matches: " + matches);
In java, I have this URL as a string:
window.location.href =
"http://localhost:8080/bladdey/shop/c6c8262a-bfd0-4ea3-aa6e-d466a28f875/hired-3";
I want to create a javascript regular expression to pull out the following string:
c6c8262a-bfd0-4ea3-aa6e-d466a28f875
To find left hand marker for the text, I could use the regex:
window\.location\.href \= \"http\:\/\/localhost:8080\/bladdey\/shop\/
However, I don't know how to get to the text between that and /hired3"
What is the best way to pull out that string from a URL using javascript?
You could split the string in tokens and look for a string that has 4 occurrences of -.
Or, if the base is always the same, you could use the following code:
String myString = window.location.href;
myString = myString.substring("http://localhost:8080/bladdey/shop/".Length());
myString = myString.subString(0, myString.indexOf('/'));
Use a lookahead and a lookbehind,
(?<=http://localhost:8080/bladdey/shop/).+?(?=/hired3)
Check here for more information.
Also, there is no need to escape the : or / characters.
You need a regex, and some way to use it...
String theLocation = "http://localhost:8080/bladdey/shop/c6c8262a-bfd0-4ea3-aa6e-d466a28f8752/hired-3";
String pattern = "(?</bladdey/shop/).+?(?=/hired3)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
note - this will still work when you change the host (it only looks for bladdey/shop/)
You can use capturing groups to pull out some content of your string.
In your case :
Pattern pattern = Pattern.compile("(http://localhost:8080/bladdey/shop/)(.+)(/hired-3)");
Matcher matcher = pattern.matcher(string);
if(matcher.matches()){
String value = matcher.group(2);
}
String param = html.replaceFist("(?s)^.*http://localhost:8080/bladdey/shop/([^/]+)/hired-3.*$", "$1");
if (param.equals(html)) {
throw new IllegalStateException("Not found");
}
UUID uuid = new UUID(param);
In regex:
(?s) let the . char wildcard also match newline characters.
^ begin of text
$ end of text
.* zero or more (*) any (.) characters
[^...]+ one or more (+) of characters not (^) being ...
Between the first parentheses substitutes $1.
Well if you want to pull out GUID from anything:
var regex = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{11,12}/i
It should really be {12} but in your url it is malformed and has just 15.5 bytes of information.
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
If I have a String in JavaScript
key=value
How do I make a RegEx that matches key excluding =?
In other words:
var regex = //Regular Expression goes here
regex.exec("key=value")[0]//Should be "key"
How do I make a RegEx that matches value excluding =?
I am using this code to define a language for the Prism syntax highlighter so I do not control the JavaScript code doing the Regular Expression matching nor can I use split.
Well, you could do this:
/^[^=]*/ // anything not containing = at the start of a line
/[^=]*$/ // anything not containing = at the end of a line
It might be better to look into Prism's lookbehind property, and use something like this:
{
'pattern': /(=).*$/,
'lookbehind': true
}
According to the documentation this would cause the = character not to be part of the token this pattern matches.
use this regex (^.+?)=(.+?$)
group 1 contain key
group 2 contain value
but split is better solution
.*=(.*)
This will match anything after =
(.*)=.*
This will match anything before =
Look into greedy vs ungreedy quantifiers if you expect more than one = character.
Edit: as OP has clarified they're using javascript:
var str = "key=value";
var n=str.match(/(.*)=/i)[1]; // before =
var n=str.match(/=(.*)/i)[1]; // after =
var regex = /^[^=]*/;
regex.exec("key=value");
string str contains somewhere within it http://www.example.com/ followed by 2 digits and 7 random characters (upper or lower case). One possibility is http://www.example.com/45kaFkeLd or http://www.example.com/64kAleoFr. So the only certain aspect is that it always starts with 2 digits.
I want to retrieve "64kAleoFr".
var url = str.match([regex here]);
The regex youβre looking for is /[0-9]{2}[a-zA-Z]{7}/.
var string = 'http://www.example.com/64kAleoFr',
match = (string.match(/[0-9]{2}[a-zA-Z]{7}/) || [''])[0];
console.log(match); // '64kAleoFr'
Note that on the second line, I use the good old .match() trick to make sure no TypeError is thrown when no match is found. Once this snippet has executed, match will either be the empty string ('') or the value you were after.
you could use
var url = str.match(/\d{2}.{7}$/)[0];
where:
\d{2} //two digits
.{7} //seven characters
$ //end of the string
if you don't know if it will be at the end you could use
var url = str.match(/\/\d{2}.{7}$/)[0].slice(1); //grab the "/" at the begining and slice it out
what about using split ?
alert("http://www.example.com/64kAleoFr".split("/")[3]);
var url = "http://www.example.com/",
re = new RegExp(url.replace(/\./g,"\\.") + "(\\d{2}[A-Za-z]{7})");
str = "This is a string with a url: http://www.example.com/45kaFkeLd in the middle.";
var code = str.match(re);
if (code != null) {
// we have a match
alert(code[1]); // "45kaFkeLd"
}βββββββββββββββββββββββββββββββββββββ
The url needs to be part of the regex if you want to avoid matching other strings of characters elsewhere in the input. The above assumes that the url should be configurable, so it constructs a regex from the url variable (noting that "." has special meaning in a regex so it needs to be escaped). The bit with the two numbers and seven letter is then in parentheses so it can be captured.
Demo: http://jsfiddle.net/nnnnnn/NzELc/
http://www\\.example\\.com/([0-9]{2}\\w{7}) this is your pattern. You'll get your 2 digits and 7 random characters in group 1.
If you notice your example strings, both strings have few digits and a random string after a slash (/) and if the pattern is fixed then i would rather suggest you to split your string with slash and get the last element of the array which was the result of the split function.
Here is how:
var string = "http://www.example.com/64kAleoFr"
ar = string.split("/");
ar[ar.length - 1];
Hope it helps