简体   繁体   English

JavaScript RegExp不起作用

[英]JavaScript RegExp doesn't work

Why these return null : 为什么这些返回null

var str="Is this all abc bbb c is";
var patt1=/is(?=bbb)/;

var str="Is this all abc bbb c is";
var patt1=/is(?=bbb)/;

var str="Is this all there is";
var patt1=/is(?=all)/; // <------ (?=all) vs (? =all)

but this returns is : 但这返回的is

var str="Is this all there is";
var patt1=/is(?= all)/;

?

(?=...)

is the regex "look-ahead" function, so here is what your regular expressions mean: 是正则表达式的“预见”功能,因此这是您的正则表达式的含义:

/is(?=bbb)/ //look for isbbb and return is
/is(?=all)/ //look for isall and return is

Both of those do not exist in your string, so you get no matches. 这两个都不存在于您的字符串中,因此您没有匹配项。

Let's take your regular expression /is(?=bbb)/ . 让我们使用正则表达式/is(?=bbb)/ Imagine a little caret at the beginning of your expression (a caret is that blinking line between letters which shows where your text cursor is - it's behind the letter it's pointing to): 想象一下,一个小在表达式的开始(插入符是闪烁的字母之间的线,显示你的文本光标是-这是它指向一个字母后头):

is(?=bbb)
^

We look for a small i in your string. 我们在您的字符串中寻找一个小i We find one in the word this . 我们在单词this找到一个。 The caret shifts: 插入符号转移:

is(?=bbb)
 ^

Is the next letter an s ? 下一个字母是s吗? It sure is. 确实是。 The caret shift again: 插入符号再次移位:

is(?=bbb)
  ^

Now something interesting happens. 现在发生了一些有趣的事情。 Now we check if the next letter is b . 现在我们检查下一个字母是否为b However even if we find it we don't advance the caret. 但是,即使找到它,我们也不会推动插入符号。

If we match the subexpression bbb only then does the caret advance to the character after the matching parenthesis (however the text matched by the subexpression isn't included in the matched string): 如果我们只匹配子表达式bbb则插入符号不会在匹配括号后前进到字符(但是,子表达式匹配的文本不包括在匹配的字符串中):

id(?=bbb)
         ^

Unfortunately no where in your string is is being followed by bbb . 不幸的isbbb后面没有字符串。 That's why you're getting null . 这就是为什么您会得到null的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM