I am using javascript regex to test a string. It should fail the text string but somehow its passing it. Any clue, what is wrong with this code?
<script>
var format = "^[a-zA-Z\.\-' ]*[a-zA-Z]+[a-zA-Z\.\-' ]*";
var testingValue = "FN306716";
var regex = new RegExp(format);
if (regex.test(testingValue) == false) {
alert('validation failed');
}
else {
alert('validation passed');
}
</script>
Just guessing that you are missing $ at the end of your regex to test full string.
var regex = /^[a-zA-Z\.\-' ]*[a-zA-Z]+[a-zA-Z\.\-' ]$/;
With this regex, your input wouldn't pass, because it contains numbers.
EDIT: I have updated it to use regex literal as pointed out in comments.
You're missing $ (end of input anchor):
Regex should be:
var format = "^[a-zA-Z.' -]*[a-zA-Z]+[a-zA-Z.' -]*$";
Also remember that - need not be escaped when used at fist and last position in character class and dot . also need not be escaped inside character class.
Live Demo: http://www.rubular.com/r/Q26cgQVJTm
Related
I'm trying to validate the value of an input text field with the following code:
function onBlurTexto(value) {
var regexNIT = "([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])";
regexCompilado = new RegExp(regexNIT);
if (!(regexCompilado.test(value))) {
alert("Wrong character in text :(");
return false;
} else {
return true;
}
}
But when i enter this text:
!65a
the function returns true (as you can see, the "!" character does not exist in the regular expression)
I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp.
How can i put this regular expression to work?
Thanks in advance.
EDIT
i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. I modified the sample. Thanks #TecBrat
You should provide the start (^) and end ($) flags to your regex. Now you are matching 65a since you have alternate sets.
This should work /^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$/g
Demo: https://regex101.com/r/zo2MpN/3
RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. In order to do the latter, you need to add start and end anchors to your regex (i.e. '^' at the start and '$' at the end, so you have "^your regex here$").
I also just noticed that your regex is currently matching only one character. You probably want to add a '+' after the parens so that it matches one or more:
"^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$"
This is wrong. the variable you use doesn't has anything. Try this instead.
var regexCompilado = new RegExp(regexNIT);
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
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.
say i have the following variables:
myId; //Email_PDF
currentHoverOnItem; //Email_PDF_english of Email_PDF_Dutch or ...
So the first value is "Email_PDF" and the second is "Email_PDF_english". What i want i when currentHoverOnItem contains myId, then something can be executed.
This is what i have so far:
var pattern = new RegExp("^/"+myId+"/$");
if (currentHoverOnItem.match(pattern))
{
//Do something
}
Is this the right way to use the regex? It should match part of the string, there can be text before or after the match.
Is this the right way to use the regex?
No! Regexes are for patterns, not for literal strings. Use indexOf
if (currentHoverOnItem.indexOf(myId) >= 0)
{
//Do something
}
Try this
var pattern = new RegExp(myId, "g");
if (currentHoverOnItem.match(pattern))
{
//Do something
}
Your pattern is "anchored", meaning that ^ and $ specifiy begin and end of your string.
To match "Email_PDF_english" in an anchored pattern you could use
^Email_PDF_(.*)$, but it won't match if your string is longer, as your comment suggests.
If it's not anchored you could test for a blank following the Email_PDF_... string, ie
Email_PDF_([^\s]*)\s+
You need not use a reg_exp here. Using indexOf will do the trick for you
if(currentHoverOnItem.indexOf(myId) != -1)
{
//Do something
}
I am facing this problem. i am getting strings like this.
'=--satya','=---satya1','=-----satya2'.
now my problem is i have to remove these special characters and print the strings like this
'satya'
'satya1'
'satya2'
please help to solve this problem?
Use String.replace:
var s = '=---satya1';
s.replace(/[^a-zA-Z0-9]/g, '');
to replace all non-letter and non-number characters or
s.replace(/[-=]/g, '');
to remove all - and = characters or even
'=---satya-1=test'.replace(/(=\-+)/g, ''); // out: "satya-1=test"
to prevent removing further - or =.
You could extract that information with a regular expression such as
/\'\=-{0,}(satya[0-9]{0,})\'/
Live example: http://jsfiddle.net/LFZje/
The regex matches
Literal '
Literal =
Zero or more -
Starts a capture group and captures
- Literal satya
- Zero or more numbers
Ends the capture group
Literal '
Then using code such as
var regex = /\'\=-{0,}(satya[0-9]{0,})\'/g;
while( (match = regex.exec("'=--satya','=---satya1','=-----satya2'")) !== null)
{
// here match[0] is the entire capture
// and match[1] is tthe content of the capture group, ie "satya1" or "satya2"
}
See the live example more detail.
Use javascript function replace which helps you to use regex for this case
var string = '=---satya1';
string = string.replace(/[^a-zA-Z0-9]/g, '');