Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annoying and weird regex problem: 'io\.' get's a match on the word 'function'

From the node REPL thing,

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

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

More weird things:

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

So it appears I'm not escaping the dot character..? But I am with the "\"... right ? I tested it on both http://www.regextester.com/ and http://regexpal.com/ and it works the way I think it's supposed to work.

What am I doing wrong ? Is the regex stuff in node.js somewhat different then what I'm used to ?

EDIT1: In Google Chrome's javascript console I get also

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

So it might be a v8 thing... right ?

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

like image 476
João Pinto Jerónimo Avatar asked Dec 09 '22 08:12

João Pinto Jerónimo


1 Answers

Your regex is right, but you have to encode it for putting it in a string, too. So, your (correct) regex looks like this:

io\.

However, The backslash is also a string escape character. In order to create a string containing that regex, you have to escape the backslash:

'io\\.'

The way you wrote it, the string actually contains io., which correctly matches function.

like image 164
Medo42 Avatar answered Dec 29 '22 00:12

Medo42