Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.match() with a regular expression returns null

I am trying to do something I thought would be pretty easy to do, which is to restrict a string to certain characters by matching a regular expression.

var value = 'FailureStr1ng'; var type = 'ALPHA'; var regex = null;  switch(type) {     case 'ALPHA':         regex = '^[a-zA-Z]+$';         break;     case 'NUMERIC':         regex = '^[0-9]+$';         break;     case 'ALPHANUMERIC':         regex = '^[a-zA-Z0-9]+$';         break; }  return value.match(regex); 

For some reason, when using the match it always returns null. Is there a way to fix this, or a better method to do this?

Note: The code here is a snippet of much larger code, and in turn the value and type variable are usually defined by another method.

like image 206
MichaelH Avatar asked Dec 29 '11 03:12

MichaelH


People also ask

What does match return in regex?

The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

Does empty regex match everything?

An empty regular expression matches everything.

Does regex match return array?

match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.

How do you match in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

You want RegExp.test, which tests a value for a match instead of retrieving the match. With your existing code, that would mean:

if(!new RegExp(regex).test(value)){     alert('Your string was invalid.'); } 

However, it would be preferable to use RegExp literals instead of strings, as they're much more efficient and clear, and less prone to error:

var value = 'FailureStr1ng'; var type = 'ALPHA'; var regex = null;  switch(type) {     case 'ALPHA':         regex = /^[a-zA-Z]+$/;         break;     case 'NUMERIC':         regex = /^[0-9]+$/;         break;     case 'ALPHANUMERIC':         regex = /^[a-zA-Z0-9]+$/;         break; }  if(!regex.test(value)) {     alert('Your string was invalid.'); } 

Even better, use a dictionary:

var expressions = {     ALPHA: /^[a-zA-Z]+$/,     NUMERIC: /^[0-9]+$/,     ALPHANUMERIC: /^[a-zA-Z0-9]+$/ };  if(!expressions[type].test(value)) {     alert('Your string was invalid.'); } 
like image 71
Ry- Avatar answered Oct 09 '22 03:10

Ry-