What is the difference between RegExp’s exec() function and String’s match() function?
exec
with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions. So:
var re = /[^\/]+/g;
var match;
while (match = re.exec('/a/b/c/d')) {
// match is now the next match, in array form.
}
// No more matches.
String.match
does this for you and discards the captured groups.
match Vs exec in JavaScript
string.match
finds the first match and returns it with the actual match, the index at which the text was found and the actual input, when the global flag is not used.string.match
just returns all the matches, when the global flag is used.
var myString = "[22].[44].[33]."; console.log(myString.match(/\d+/)); // [ '22', index: 1, input: '[22].[44].[33].' ]console.log(myString.match(/\d+/g));// [ '22', '44', '33' ]
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()
).
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:
Conclusion
Use .test
if you want a faster boolean check. Use .match
to retrieve all matches when using the g
global flag.
Javascript Regular Expression Difference
I'm repeating myself about this issue, but let's have a go at it one more time.
First, the browser is very good at parsing HTML. Parsing HTML is its primary feature. So, let the browser do its job:
source = `<input id="buttonClickOne" type="button" value="Click 1" @click="buttonOneClicked">`
dom = new DOMParser().parseFromString(source, 'text/html')
Now you have a fully parsed object which supports all the nice DOM features you're used to (I hope) such as:
dom.body.firstElementChild.getAttribute('@click')
// returns "buttonOneClicked"
I know, it may look like a slight overkill in your example, but it's not that expensive and I assume your example is simplified anyway.
Performance - match() vs. exec() for extracting a single value
It'd use match
because it can be kept on one line, but it's a matter of taste.
Difference of regex in python and google app script (backend engine related?)
First of all, you need to use \\
before .
in the GAS regex declaration, as the literal backslash forms a regex escape sequence.
Now, it seems that GAS non-capturing group implementation is buggy.
If you run your regex in GAS and print the Match
object, you will see
[18-01-26 08:49:07:198 CET] [<a class=""email"" href=""mailto:SOisAwesome@hello.edu"">,
a class=""email"" href=""mailto:SOisAwesome@hello.edu, "">]
That means, the non-capturing group got "merged" with the first capturing group skipping the first char.
Here are some more experiments:
Logger.log(new RegExp("(?:;\\w+):(\\d+)").exec(";er:34")); // = null, expected [;er:34, 34]
Logger.log(new RegExp("(?:e\\w+):(\\d+)").exec(";er:34")); // = null, expected [er:34, 34]
Logger.log(new RegExp("(?:\\w+):(\\d+)").exec(";er:34")); // = [er:34, 34], as expected
To fix the issue, you may remove the non-capturing parentheses, as \d
= (?:\d)
.
RegExp for .exec() and .split() are not working the same
The pattern
Your split pattern has a variable length look-behind assertion, which causes overlaps:
Cristoforo Colombo Airport, Genoa, Italy (GOA) - Augsburg -
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Satisfies the assertion
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Also satisfies the assertion
About exec
You only saw one match being returned with exec
, because the /g
(global) flag wasn't specified; with the global flag enabled, calling it once will return the first match, but it returns another result if you call it again:
const a = "Cristoforo Colombo Airport, Genoa, Italy (GOA) - Augsburg - Muehlhausen Airport, Munich, Germany (AGB)"const reg = /(?<=,.*,.*) - /glet match
while ((match = reg.exec(a)) !== null) { console.log(`Found ${match[0]}. Next starts at ${reg.lastIndex}.`);}
REGEX: match and exec returns different results
As described in String.prototype.match() MDN documentation:
if you want to obtain capture groups and the global flag is set, you
need to use RegExp.exec() instead.
So, to obtain the same result with String.prototype.match()
, remove the g
flag from the regular expression:
let regexp = /Rim.*?vert\s(\d*)cm/ //<-- Removed the "g" flag.let content = "BEONE SPS SPIRIT, 2012y.b.,26 Rim - BEONE aluminium, vert 51cm «L»,ЕТТ600mm, 835 37 38";
let resultMatch = content.match(regexp);console.log('result with match:', resultMatch);
let resultExec = regexp.exec(content);console.log('result with exec:', resultExec);
Related Topics
How to Get All Arguments of a Function as Single Object Inside That Function
How to Geocode 20 Addresses Without Receiving an Over_Query_Limit Response
JavaScript Module Pattern with Example
Fire Greasemonkey Script on Ajax Request
How to Disable Tree Shaking in Rollupjs
Uint8Array to String in JavaScript
Push Is Overwriting Previous Data in Array
What Do {Curly Braces} Around JavaScript Variable Name Mean
Angular 2 Dependency Injection in Es5 and Es6
Passing a Function with Parameters as a Parameter
Determine Which Element the Mouse Pointer Is on Top of in JavaScript
Deprecation Warning in Moment.Js - Not in a Recognized Iso Format
Ignore Errors for Self-Signed Ssl Certs Using the Fetch API in a Reactnative App
How to Use a Numeric Type as an Object Key