Well, I just don't seem to understand certain things about RegExp
.
Can someone please shed some light on me? Are there some implicit words in RegExp
which result in a 开发者_JAVA百科nonmatch? My assumption is that the substring "slt" contains some hidden top secret James Bond sign which makes the RegExp
fail.
Demo to fiddle around: working demo
//does not work
var funcArgString="c09__id slt ccc";
var myRegExp = new RegExp("([^ \s]*) ([^ \s]*) ([^ \s]*)","g");
alert(myRegExp.exec(funcArgString));
//works... why???
var funcArgString="c09__id abcdefg ccc";
var myRegExp = new RegExp("([^ \s]*) ([^ \s]*) ([^ \s]*)","g");
alert(myRegExp.exec(funcArgString));
//works as well
var funcArgString="c09__id slt ccc";
var myRegExp = new RegExp("(.*) (.*) (.*)","g");
alert(myRegExp.exec(funcArgString));
If you you want to use a backslash \
in you regex, you have to use two \\
if you pass the expression as string:
var myRegExp = new RegExp("([^\\s]*) ([^\\s]*) ([^\\s]*)","g");
The backslash is the escape character in JavaScript strings and it will be evaluated as such. To insert a literal backslash, you have to escape it (hence the double backslash).
Also note that you can omit the extra space in the character group, as it is already covered by \s
.
I assume JavaScript is discarding \s
as invalid character sequence and takes s
literally.
This is the resulting expression of you only use one backlash:
> new RegExp("([^\s]*) ([^\s]*) ([^\s]*)","g");
/([^s]*) ([^s]*) ([^s]*)/g
My assumption is that the
slt
contains some hidden top secret james bond sign which makes the regexp fail
Yes, the villain is s
in this case ;) ([^s]*)
matches every character but an s
so the first string is not matched.
Updated DEMO
Alternatively, you can use a regex literal. As it is literal (and not in a string), we don't have to escape the backlash:
var funcArgString="c09__id slt ccc";
var myRegExp = /([^\s]*) ([^\s]*) ([^\s]*)/g;
alert(myRegExp.exec(funcArgString));
Also, instead of using [^\s]
you can use \S
, which is the same thing.
精彩评论