Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Javascript Regex matching every second time?

Tags:

I'm defining a regex object and then matching it in a loop. It only matches sometimes, to be precise - every second time. So I created a smallest working sample of this problem.

I tried this code in Opera and Firefox. The behavior is the same in both:

>>> domainRegex = /(?:\.|^)([a-z0-9\-]+\.[a-z0-9\-]+)$/g; /(?:\.|^)([a-z0-9\-]+\.[a-z0-9\-]+)$/g  >>> domainRegex.exec('mail-we0-f174.google.com'); Array [".google.com", "google.com"] >>> domainRegex.exec('mail-we0-f174.google.com'); null >>> domainRegex.exec('mail-we0-f174.google.com'); Array [".google.com", "google.com"] >>> domainRegex.exec('mail-we0-f174.google.com'); null >>> domainRegex.exec('mail-we0-f174.google.com'); Array [".google.com", "google.com"] >>> domainRegex.exec('mail-we0-f174.google.com'); null 

Why is this happening? Is this behaviour documented? Is there a way around, other than defining the regex inside loop body?

like image 700
GDR Avatar asked Aug 27 '13 10:08

GDR


People also ask

How to escape RegEx JavaScript?

To match a literal backslash, you need to escape the backslash. For instance, to match the string "C:\" where "C" can be any letter, you'd use /[A-Z]:\\/ — the first backslash escapes the one after it, so the expression searches for a single literal backslash.

How does RegEx work in JavaScript?

Regular expressions are a sequence of characters that are used for matching character combinations in strings for text matching/searching. In JavaScript, regular expressions are search patterns (JavaScript objects) from sequences of characters. RegExp makes searching and matching of strings easier and faster.

How to replace regular expression in JavaScript?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

Does regex match anything?

Matching a Single Character Using Regex ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.


1 Answers

exec() works in the manner you have described; with the /g modifier present, it will return a match, starting from lastIndex with every invocation until there are no more matches, at which point it returns null and the value of lastIndex is reset to 0.

However, because you have anchored the expression using $ there won't be more than one match, so you can use String.match() instead and lose the /g modifier:

var domainRegex = /(?:\.|^)([a-z0-9\-]+\.[a-z0-9\-]+)$/; 'mail-we0-f174.google.com'.match(domainRegex); // [".google.com", "google.com"] 
like image 72
Ja͢ck Avatar answered Oct 06 '22 08:10

Ja͢ck