'function'.search('io\.') 5 I really need it...">

Annoying and weird regexp problem: 'io \.' get a match for the word "function"

From node REPL,

> 'function'.search('io\.') 5 

I really need it to match only io. not a "function" or anything just with "io" in the middle ...

Stranger things:

 > 'io'.search('io\.') -1 > 'ion'.search('io\.') 0 

So it looks like I'm not avoiding the dot symbol.? But I'm with "\" ... right? I tested it on http://www.regextester.com/ and http://regexpal.com/ and it works the way I think it should work.

What am I doing wrong? Is the regex material in node.js slightly different than what I'm used to?

EDIT1: In javascript google chrome console i also get

 'function'.search('io\.') 5 

So, that could be the v8 thing ... right?

EDIT2: I get the same results from the Firefox javascript console, so this is not a v8 thing ... What happens here? I'm really confused ...

+4
source share
2 answers

Your regular expression is correct, but you must also encode it to put it in a string. So your (regular) regex looks like this:

 io\. 

However, the backslash is also an escape character in the string. To create a string containing this regular expression, you need to avoid the backslash:

 'io\\.' 

As you wrote it, the line actually contains io. which matches function .

+8
source

The problem is that the backslash is used as an escape character at two levels: in string literals and in regular expressions. For example, '\\' is a string containing one backslash (which you can see if you enter it in the REPL).

There are two options:

  • Holds backslash: '\\.' is a string containing a backslash and a period, which is a regular expression that matches the period.

  • use regex literal: /io\./

     > 'function'.search(/\./) -1 
+6
source

All Articles