Regular expression match ! - javascript

I am trying to find for the string of the format abc1234. I can compare character taking at each index whether is alpha or numeric and get the result. Instead wrote for a pattern match but couldn't succeed. Could some one know me where I am going wrong ?
var clid = "mxv4013" ;
if(clid.match("/[a-z]{3}(?=[0-9]{4})/i") != null){
alert("success") ;
}
Thanks.

You don't need the quotes, JavaScript has regex literals:
var clid = "mxv4013" ;
if(clid.match(/[a-z]{3}(?=[0-9]{4})/i)){
alert("success") ;
}
You can also remove the != null check - match will return a true value on success and a falsy value on fail. In addition, the look-ahead is a little strange, you can use /[a-z]{3}\d{4}/i, or, to validate the whole string and avoid partial matching, /^[a-z]{3}\d{4}$/i.

String#match takes a regexp instead of a string for its parameter.
You are looking for:
'mxv4013'.match(/[a-z]{3}(?=[0-9]{4})/i)
Or, more simply:
'mxv4013'.match(/[a-z]{3}\d{4})/i)

Related

Is there a method that returns only the match or first variable match of a RegEx in ActionScript or null?

Is there a method yet that returns only a match and null if there is no match?
It may be a brain freeze but is there a method that just returns the match and null if not?
For example, if I want to just return the first variable or null otherwise:
var value:String = "image/png".toLowerCase();
var result:String = value.find(/image/(png|jpg|jpeg|gif)/);
if (result=="png") {
// do something
}
I know there's replace and exec and match and they return arrays etc but I'm just looking for a method that returns my first match or null.
If there isn't this a function like this, I wish there was. How to god I wish there was.
There is no specific method that does that. The closest method is String.match or RegExp.exec and it makes little difference here since the regex has no global modifier. Once you use a regex with a global modifier, you will have no choice but to use RegExp.exec.
Using String.match or RegExp.exec you can check if the result is null and if it's not null then extract the Group 1 value to check if it is png:
var pattern:RegExp = /image\/(png|jpg|jpeg|gif)/;
var str:String = "image/png".toLowerCase();
var m:Array = pattern.exec(str);
if (m != null)
{
if (m[1] == "png") {
// Do stuff
}
}
Note that a / must be escaped in a regex literal.
You can also contract the pattern a bit to (png|jpe?g|gif), but though it will work better internally, it will become less readable.

Convert string to function with parameters

I am struggling with writing a regular expression to turn the string
"fetchSomething('param1','param2','param3')"
into the proper function call. I can do it with some splitting and substrings but would rather do it with a .match using capture groups for efficiency's sake (and my own education).
However when I use
'something("stuff","moreStuff","yetMoreStuff")'.match(/(?:\(|,)("?\w+"?)/g)
I get
["("stuff"", ","moreStuff"", ","yetMoreStuff""]
Which is the same result regardless of the ?:, this confuses me since I thought ?: would cause it to ignore the first capture group? Or am I completely miss understanding capture groups?
You get the whole string when you have the g flag active. If you're going only after the sub-matches, then you will need to use .exec and a loop:
var regex = /(?:\(|,)("?\w+"?)/g;
var s = 'something("stuff","moreStuff","yetMoreStuff")';
var match, matches=[];
while ( (match=regex.exec(s)) !== null ) {
matches.push(match[1]);
}
alert(matches);
jsfiddle

Regular expression to match 0 or 1

I need a regexp to match either 0 or 1 entered into a field and no other characters at all, neither numeric nor alphas. How can I do it?
Single character, 0 or 1:
/^[01]$/
Multiple 0s or 1s (any order, no other characters):
/^[01]+$/g
Demo (Just add a + for the second example. The gm at the end in the demo is just for the example because there are multiple lines for test cases)
A simple 0|1 expression should work.
([01])
http://rubular.com/r/TMu6vsx6Dn
If you only want the first occurrence, this will work as well.
(^[01])
http://rubular.com/r/i3brvRutCg
Try this regex: /^(0|1)$/
Example:
/^(0|1)$/.test(0); // true
/^(0|1)$/.test(1); // true
/^(0|1)$/.test(2); // false
/^(0|1)$/.test(1001) // false
I would suggest simple string evaluation here since you have only two known acceptable values in the input string:
var input; // Your input string assume it is populated elsewhere
if (input === '0' || input === '1') {
// Pass
}
Note the use of strict string comparison here to eliminate matches with truthy/falsey values.
If you are really hell-bent on a regex, try:
/^[01]$/
The key here is the beginning ^ and ending $ anchors.

Javascript regex match for string "game_1"

I just can't get this thing to work in javascript. So, I have a text "game_1" without the quotes and now i want to get that number out of it and I tried this:
var idText = "game_1";
re = /game_(.*?)/;
found = idText.match(re);
var ajdi = found[1];
alert( ajdi );
But it doesn't work - please point out where am I going wrong.
If you're only matching a number, you may want to try
/game_([0-9]+)/
as your regular expression. That will match at least one number, which seems to be what you need. You entered a regexp that allows for 0 characters (*) and let it select the shortest possible result (?), which may be a problem (and match you 0 characters), depending on the regex engine.
If this is the complete text, then there is no need for regular expressions:
var id = +str.split('_')[1];
or
var id = +str.replace('game_', '');
(unary + is to convert the string to a number)
If you insist on regular expression, you have to anchor the expression:
/^game_(.*?)$/
or make the * greedy by omitting the ?:
/game_(.*)/
Better is to make the expression more restrictive as #Naltharial suggested.
Simple string manipulation:
var idText = "game_1",
adji = parseInt(idText.substring(5), 10);
* means zero or more occurrences. It seems that combining it with a greediness controller ? results in zero match.
You could replace * with + (which means one or more occurrences), but as #Felix Kling notes, it would only match one digit.
Better to ditch the ? completely.
http://jsfiddle.net/G8Qt7/2/
Try "game_1".replace(/^(game_)/, '')
this will return the number
You can simply use this re /\d+/ to get any number inside your string

regular expression not working when provided in double quotes in javascript

I am trying to use regular expession in javascript but it is not working. My custom control contains property called RegEx which is provided by user and I need to validate the input value against this regex. As properties in JS will be in double quotes("") the regualr expression fails(case -1). Case 2 succeeds thought both the cases regualr expression is same, the only difference is case- 1 it goes as double quotes. can somebody tell me why it is not working.
RegexExp="/^\d{5}$/"- at my aspx page
var value = "11111";
if(value.toString().search($(element).attr('RegexExp')) != -1)
{
return true;
}
else
{
return false;
}
var reg = /^\d{5}$/;
if(value.toString().search(reg) != -1)
{
return true;
}
else
{
return false;
}
Do this instead:
var reg = new RegExp($(element).attr('RegexExp'));
Update: you also need to strip the / characters, as these shouldn't be given to the RegExp constructor:
var regexExp = $(element).attr('RegexExp');
var reg = new RegExp(regexExp.substring(1, regexExp.length - 1));
I assume that the code that you posted is part of the function from the return statements, but if it is not, your first problem is that return is not allowed to be used out side of functions.
In any case, try the following. You can create a RegExp from a string by using its formal constructor
value.search(new RegExp($(element).attr('RegexExp')));
Also, you do not need to use toString() on value since it is already a string and your code is unnecessarily verbose. The following is equivalent to your first if else statement
return value.search(new RegExp($(element).attr('RegexExp'))) != -1;
Edit:
If you want to be able to pass in an expression as "/[expression]/" or "/[expression]/gi", you can do the following:
var toRegExp = function(regexString) {
var expression = regexString.substr(1), // remove first '/'
closingSlash = expression.lastIndexOf("/"); // find last '/'
return new RegExp(
// Expression: remove everything after last '/'
expression.substr(0, closingSlash),
// Flags: get everything after the last '/'
expression.substr(closingSlash+1)
);
}
....
value.search( toRegExp($(element).attr('RegexExp')) );
First, don't use a custom attribute to hold a regular expression. Second, "RegexExp" is redundant — that's like saying "regular expression expression". Third, to convert from a String to a RegExp, you have to wrap the string with new RegExp(); JavaScript is not weakly typed. That said, assuming that the regular expression isn't being set server-side, I'd recommend using jQuery's data API. It has the added advantage that it can store regular expression objects directly.
To set:
jQuery.data($(element).get(0), "regexp", /^\d{5}$/);
To get:
jQuery.data($(element).get(0), "regexp");
But ultimately, what you really want is the jQuery Validation plugin. It does everything you need and then some. Incidentally, it uses the data API internally to work its magic.
Documentation
The /.../ syntax is used to declare a regular expression object in Javascript, so you shouldn't use that to specify a regular expression pattern, it should be just regexp="^\d{5}$" as the attribute.
The search method takes a regular expression object as parameter, so you have to create a regular expression object from the string that you get from the attribute:
var reg = new RegExp($(element).attr('regexp'));
if (value.toString().search(reg) != -1) {
(You see the similarity with your second case?)
Or as a single expression:
if (value.toString().search(new RegExp($(element).attr('regexp'))) != -1) {

Categories

Resources