Regex.Test V.S. String.Match to Know If a String Matches a Regular Expression

regex.test V.S. string.match to know if a string matches a regular expression

Basic Usage

First, let's see what each function does:

regexObject.test( String )

Executes the search for a match between a regular expression and a specified string. Returns true or false.

string.match( RegExp )

Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or null if there are none.

Since null evaluates to false,

if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}

Performance

Is there any difference regarding performance?

Yes. I found this short note in the MDN site:

If you need to know if a string matches a regular expression regexp, use regexp.test(string).

Is the difference significant?

The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:

test vs match | Performance Test

Conclusion

Use .test if you want a faster boolean check. Use .match to retrieve all matches when using the g global flag.

Check whether a string matches a regex in JS

Use regex.test() if all you want is a boolean result:

console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true

How to correctly check if a string match regex in javascript

/^"[^"]*"(?:\s*;\s*"[^"]*")+;?$/
---2---
---------3---------
-4

... can be broken down into ...

  1. /^ ... $/
  2. "[^"]*"
  3. (?:\s*;\s*"[^"]*")+
  4. ;?

... which then translates to ...

  1. In between new line start and line end ...
  2. match a double quote, followed by an optional sequence of characters, each character not being a double quote, followed by a double quote.
  3. group ( ... ) the following match but do not capture it (?: ... ) and force this pattern to be present at least once (?: ... )+ ... within this group ...
    • match the sequence of an optional whitespace (WS) a semicolon and another optional WS followed by the pattern already described with/under (2).
  4. the entire match is allowed to end with none or exactly one semicolon.

const regex = /^"[^"]*"(?:\s*;\s*"[^"]*")+;?$/;

const test1 = `"hello"; "world";`;
const test1a = `"hello" ; "world" ;"world"; "world"`;
const test2 = `"hello" ; "world"`;
const test2a = `"hello";"world" ; "world";"world"`;

const test3 = `"hello; "world"`;
const test4 = `"hello"; world`;
const test5 = `"hello""world"`;

const test6 = `"hello ; world;";"hello ;world"`;

const test6a = `"hello ;world;" "hello; world"`;
const test6b = `"hello; world"`;

//should be true
console.log("test1", regex.test(test1));
console.log("test1a", regex.test(test1a));
console.log("test2", regex.test(test2));
console.log("test2a", regex.test(test2a));

console.log("test6", regex.test(test6));

//should be false
console.log("test3", regex.test(test3));
console.log("test4", regex.test(test4));
console.log("test5", regex.test(test5));

console.log("test6a", regex.test(test6a));
console.log("test6b", regex.test(test6b));
.as-console-wrapper { min-height: 100%!important; top: 0; }

what is the difference between .match and .test in javascript

First off, .exec() and .test() are methods on a regular expression object. .match() is a method on a string and takes a regex object as an argument.

.test() returns a boolean if there's a match or not. It does not return what actually matches.

.match() and .exec() are similar. .match() is called on the string and returns one set of results. .exec() is called on the regex and can be called multiple times to return multiple complex matches (when you need multiple matches with groups).

You can see some examples of how you can use multiple successive calls to .exec() here on MDN.

You would likely use .test() if you only want to know if it matches or not and don't need to know exactly what matched.

You would likely use .match() if you want to know what matched and it meets your needs (e.g. you don't need something more complex with multiple calls to .exec()).

Test whether a string matches a regex?

you can use the test method in order to get the result as a Boolean

function isEqual(str){  return /\/users\/(.+)/.test(str);    // code}
// Some examples of requests
console.log(isEqual('/users/1'));console.log(isEqual('/users/1/Nikita'));console.log(isEqual('/users'));

Check if a string matches a regex in Bash script

You can use the test construct, [[ ]], along with the regular expression match operator, =~, to check if a string matches a regex pattern (documentation).

For your specific case, you can write:

[[ "$date" =~ ^[0-9]{8}$ ]] && echo "yes"

Or more a accurate test:

[[ "$date" =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
# |\______/\______*______/\______*__________*______/|
# | | | | |
# | | | | |
# | --year-- --month-- --day-- |
# | either 01...09 either 01..09 |
# start of line or 10,11,12 or 10..29 |
# or 30, 31 |
# end of line

That is, you can define a regex in Bash matching the format you want. This way you can do:

[[ "$date" =~ ^regex$ ]] && echo "matched" || echo "did not match"

where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.


In other shells you can use grep. If your shell is POSIX compliant, do

(echo "$date" | grep -Eq  ^regex$) && echo "matched" || echo "did not match"

In fish, which is not POSIX-compliant, you can do

echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"

Caveat: These portable grep solutions are not water-proof! For example, they can be tricked by input parameters that contain newlines. The first mentioned bash-specific regex check does not have this issue.

Fastest way to check if a string matches a regexp in ruby?

Starting with Ruby 2.4.0, you may use RegExp#match?:

pattern.match?(string)

Regexp#match? is explicitly listed as a performance enhancement in the release notes for 2.4.0, as it avoids object allocations performed by other methods such as Regexp#match and =~:

Regexp#match?

Added Regexp#match?, which executes a regexp match without creating a back reference object and changing $~ to reduce object allocation.

Javascript RegExp Check for Either String or Integer

var passVal = typeof(valueToMatch) === 'number'? valueToMatch.toString() : valueToMatch
var regExp = new RegExp(passVal , 'gi');
item.ssn.match(regExp)

You should check the value before passing through regex expression.



Related Topics



Leave a reply



Submit