RegEx \w not working

Posted by Kyrock on Sun 14 Oct 2012 08:08 PM — 3 posts, 21,225 views.

#0
So, their may already be a way of doing this, but I'm trying to make the toString methods of my objects return the constructor name. But, when I tried to use the javascript RegEx the \w (word character) doesn't work. So I create a alias called test with this script.


world.Note("testing");
var pattern = /\w/g;
var text = "this those that.";
var result = text.match(pattern);
if (result != null) {
  for (var i = 0;i < result.length;i++) {
    world.Note(i + ":" + result);
  }
}


This just outputs "testing". If I use the equivalent range set though:


world.Note("testing");
var pattern = /[a-zA-z0-9_]/g;
var text = "this those that.";
var result = text.match(pattern);
if (result != null) {
  for (var i = 0;i < result.length;i++) {
    world.Note(i + ":" + result);
  }
}

I get testing and each letter noted. I tried it in firefox and \w works fine.
USA #1
Are you editing from MUSHclient's alias, trigger, or timer dialogs? If so, you need to escape any backslashes, because MUSHclient pre-processes the text content before passing it on to the script engine.
world.Note("testing");
var pattern = /\\w/g;
var text = "this those that.";
var result = text.match(pattern);
if (result != null) {
  for (var i = 0;i < result.length;i++) {
    world.Note(i + ":" + result[i]);
  }
}


Because MUSHclient sees "\w", which is an invalid escape sequence, it replaces it with "w". There are no "w" characters in your test string, so nothing is matched. If you use "\\w" instead, MUSHclient will process that into "\w", then JScript will get ahold of it and properly identify it as the word character class.

[EDIT]: Hilariously, the forums do something similar, so when I want to show "\\w" I need to type "\\\\w".
Amended on Sun 14 Oct 2012 08:22 PM by Twisol
#2
heh, that's a lot of slashes and yeah, that did the trick. Thanks