Regular expression to match a number range in JavaScript - javascript

I'm having problem with JavaScript regular expressions. I want to match real numbers form 1 to 5. Precission is in two digits. My code is but it doesnt work.
function validate_prosjek(nmb)
{
var pattern= new RegExp(/[1-4]\.[0-9][0-9]|5\.00/);
return pattern.test(nmb);
}
It recognizes real numbers higher than 5.

You need to "anchor" your regexp with ^ and $ to match the beginning and end of the string, respectively:
var pattern = /^([1-4]\.[0-9][0-9]|5\.00)$/;
You also need to escape the . because it's a special character in regexps, and there's no need to call new RegExp if the regexp is already in /.../ synax.

Related

JavaScript regular expression to check single special character to occur once in a string

I have a regular expression like this
var regEx = /^([0-9a-z]{7})$|^([0-9a-z-]){8}$/ig;
I have to check if the '-'(hyphen) occurs only once in the input string if the string length is 8.
I can check it using javascript, But i want to know if it can be done with regular expressions
You can use the negative lookahead for this:
/^[0-9a-z]{7}$|^(?!.*-.*-)[0-9a-z-]{8}$/ig
update
The regex below allows no hyphen, if length is 7, and it allows one (and no more) hyphen if the length is 8:
^[0-9a-z]{7}$|^(?=[^-]*-[^-]*$)[0-9a-z-]{8}$

Why does this regular expression evaluate to false in javascript?

I'm looking for a string that is 0-9 digits, no other characters.
This is alerting me with a "false" value:
var regex = new RegExp('^[\d]{0,9}$');
alert(regex.test('123456789'));
These return true, and I understand why (The ^ and $ indicate that the whole string needs to match, not just a match within the string) :
var regex = new RegExp('[\d]{0,9}');
alert(regex.test('123456789'));
-
var regex = new RegExp('[\d]{0,9}');
alert(regex.test('12345678934341243124'));
and this returns true:
var regex = new RegExp('^[\d]{0,9}');
alert(regex.test('123456789'));
So why, when I add the "$" at the end would this possibly be failing?
And what do I need to do to fix it?
When you use
var regex = new RegExp('^[\d]{0,9}$');
syntax, you'll get regex as
/^[d]{0,9}$/
Note the \d is turned into d.
This regex /^[d]{0,9}$/ will match only the d zero to nine times.
RegExp uses string to define regex, the \ is also used as escape symbol in the string, so \ in \d is considered as the escape character.
Escape the \ by preceding it with another \.
var regex = new RegExp('^[\\d]{0,9}$');
I'll recommend you to use regex literal syntax rather than the confusing RegExp syntax.
var regex = /^\d{0,9}$/;
EDIT:
The reason you get true when using var regex = new RegExp('^[\d]{0,9}'); is because the regex implies that the string should start with any number of d include zero to nine. So, event when the string does not starts with d the condition is stratified because of 0 as the minimum no of occurrences.
You might want to check if the string starts with one to nine digits.
var regex = /^\d{1,9}$/;
You should use the regular expression literal (without quotes and using the beginning and ending slashes) when defining the RegExp object. This is the recommended approach when the regular expression will remain constant, meaning it does not need to be compiled every time it is used. This gives you the desired result:
var regex = new RegExp(/^[\d]{0,9}$/);
Because $ means End of line, and your string does not have an end of line as last character
May be you are looking for "\z"

Why does .NET match my regex but Javascript does not?

I needed a regular expression to match fractions and mixed numbers, but not allow zero for any of the distinct values (whole number, numerator, denominator).
I found a solution that was close to what I needed and modified it a little.
I then tested it on RegexHero which uses the .NET regex engine.
The regular expression matched "1 1/2" as I would expect, but when I tried the same regular expression in Javascript with the .test() function, it did not match it.
My suspicion is that it has something to do with how each engine handles the whitespace, but I'm not sure. Any idea why it matched on one but not the other?
The regular expression was:
^([1-9][0-9]*/[1-9][0-9]*|[1-9][0-9]*(\s[1-9][0-9]*/[1-9][0-9]*)?)$
EDIT:
I tried Jasen's suggestion, but my test is still failing.
var ingredientRegex = /^([1-9][0-9]*\/[1-9][0-9]*|[1-9][0-9]*(\\s[1-9][0-9]*\/[1-9][0-9]*)?)$/;
function isValidFraction(value) {
return ingredientRegex.test(value);
}
It is being tested with Jasmine.
it("should match a mixed number", function() {
expect(isValidFraction("2 1/2")).toBe(true);
});
SOLUTION:
It is working now. I needed to escape the "/" characters, but I did not need to escape the "\s" as Jasen suggested.
You need to mind your escapes. The \s backslash in the character class needs escaping.
var regex = new RegExp("^([1-9][0-9]*/[1-9][0-9]*|[1-9][0-9]*(\\s[1-9][0-9]*/[1-9][0-9]*)?)$");
var str = "1 1/2";
console.log(regex.test(str)); // true
This method requires different escapes for the / character now.
var regex2 = /^([1-9][0-9]*\/[1-9][0-9]*|[1-9][0-9]*(\s[1-9][0-9]*\/[1-9][0-9]*)?)$/;
console.log(regex2.test(str)); // true
MDN RegExp

regex that checks that a string is between two lengths and has only letters and numbers

I'm trying to validate a username field in my form via client-side valdiation and I'm having some trouble.
I'm trying to use match them against regexs, which seems to work for my password strength/match. However when I try and change the regular expression to one that is suitable for usernames it doesn't work.
This is the regular expression that works, it checks to see if the length is at least 6 chars long.
var okRegex = new RegExp("(?=.{6,}).*", "g");
This is the other regular expression which does not work:
var okRegex = new RegExp("/^[a-z0-9_-]{3,16}$/");
How do I write a regex that performs username validation? (That it's of a certain length, has only letters and numbers)
You're mixing regex literals with the RegExp constructor. Use one or the other, but not both:
okRegex = new RegExp('^[a-z0-9_-]{3,16}$');
or
okRegex = /^[a-z0-9_-]{3,16}$/;
As #zzzzBow answered you are mixing up two ways of using regular expressions. Choose one or the other. Now, a break down:
^ Matches the beginning of the string (that means that the string must start with whatever follows).
[a-z0-9_-] Matches the charecters a-z, A-Z, digits 0-9 _ (underscore) and - (dash/hyphen).
{3,16} States that there must be 3-16 occurences from the above character class.
$ Matches the end of the string, so the can't be anything after the 16 characters above.
Hope that helps.

Javascript Regex Object Doesn't Recognize {n,m}

I'm trying to write a regular expression in JS to recognize any digit up to seven times, followed by a "-" followed by 2 digits followed by "-" followed by a single digit. This is the simple regex I have:
/\d{1,7}-\d{2}-\d/g
This should match strings like:
123-12-7
1-12-7
1234567-12-7
but not 12345678-12-1
However, the above is returning true. The regex returns true when there is any number of digit in the first group.
Does the JavaScript Regex object not support {n,m}?
Here is an example of what I am talking about.
var pattern = new RegExp(/\d{1,7}-\d{2}-\d/);
alert(pattern.test("12345678-13-1"));
http://jsfiddle.net/XTRAc/1/ live example
It matches 2345678-13-1. You need to anchor it to the beginning and end of your string:
/^\d{1,7}-\d{2}-\d$/
Note though, that (as Rocket Hazmat pointed out) you do not need to use the RegExp constructor if you use a regex literal (something without string quotes).
JSFiddle
It does support the {min,max}-syntax, but .match and .test() try to find matching substrings. You will have to include start and end anchors. Also notice that you should either use the RegExp constructor to build a regex from a string or a regex literal, but not both (see MDN: creating regexes).
/^\d{1,7}-\d{2}-\d$/
new RegExp("^\\d{1,7}-\\d{2}-\\d$") // the worse choice
You are constructing your regex incorrectly. Try this (note the anchors, which ensure the string consists of nothing but your pattern):
var pattern= /^\d{1,7}-\d{2}-\d$/;
Otherwise subsets of the existing string will match your regex.
If you need to validate entire input string, use regex pattern
/^\d{1,7}-\d{2}-\d$/
If you need to validate entire line of input string, use regex pattern
/^\d{1,7}-\d{2}-\d$/mg
If you need to find matches within input string, use regex pattern
/(?:\D|^)(\d{1,7}-\d{2}-\d)(?!\d)/g
...and use $1 as a result.
It does support the {n,m} part, the problem here is that your example matches 2345678, so you would need a way of matching the character before the first set of digits

Categories

Resources