Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match() returns array with two matches when I expect one match

Consider the following example:

<html>
<body>

<script type="text/javascript">

var str="filename.jpg";

var pattOne = new RegExp('\.[^\.]*$');
var pattTwo = new RegExp('(\.[^\.]*$)');
var pattThree = new RegExp('(\.[^\.]*$)', 'g');

document.write(str.match(pattOne));
document.write('<br>');
document.write(str.match(pattTwo));
document.write('<br>');
document.write(str.match(pattThree));

</script>
</body>
</html>

Here is the result:

.jpg
.jpg,.jpg
.jpg

I expect this result:

.jpg
.jpg
.jpg

Why placing parenthesis around the regular expression changes the result? Why using 'g' modifier changes again the result?

like image 980
Vasil Avatar asked Jan 25 '12 12:01

Vasil


People also ask

What does the match () method return?

The MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range. For example, if the range A1:A3 contains the values 5, 25, and 38, then the formula =MATCH(25,A1:A3,0) returns the number 2, because 25 is the second item in the range.

What does match () return in JavaScript?

JavaScript String match() The match() method returns an array with the matches. The match() method returns null if no match is found.

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 does match work in Java?

Java - String matches() MethodThis method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).


1 Answers

From String.prototype.match [MDN]:

If the regular expression does not include the g flag, returns the same result as regexp.exec(string).

Where the RegExp.prototype.exec documentation [MDN] says:

The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

So as you introduced a capture group in the second expression, the first element is the whole match and the second contains the content of the capture group, which, in your example, is the whole match as well.
The first expression does not have a capture group, so you only get back the match.

Back to the match documentation:

If the regular expression includes the g flag, the method returns an Array containing all matches. If there were no matches, the method returns null.

With the g modifier, only matches are returned, but not the content of capture groups. In your string there is only one match.

like image 128
Felix Kling Avatar answered Oct 11 '22 17:10

Felix Kling