Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在特定位置启动时,将正则表达式与输入的开始匹配_Javascript_Regex - Fatal编程技术网

Javascript 在特定位置启动时,将正则表达式与输入的开始匹配

Javascript 在特定位置启动时,将正则表达式与输入的开始匹配,javascript,regex,Javascript,Regex,在Javascript中使用RegExp时,如果希望将正则表达式与输入的开头匹配,可以像这样使用^ var regEx = /^Zorg/g; regExp.exec( "Zorg was here" ); // This is a match regExp.exec( "What is Zorg" ); // This is not a match 当在字符串中的其他位置开始匹配时,这不起作用 var regEx = /^Zorg/g; regExp.lastIndex = 5; r

在Javascript中使用RegExp时,如果希望将正则表达式与输入的开头匹配,可以像这样使用^

var regEx = /^Zorg/g;  
regExp.exec( "Zorg was here" );  // This is a match
regExp.exec( "What is Zorg" );  // This is not a match
当在字符串中的其他位置开始匹配时,这不起作用

var regEx = /^Zorg/g;
regExp.lastIndex = 5;
regExp.exec( "What Zorg?" );  // This is not a match but i want it to
根据mozilla文档,您应该能够通过使用regExp上的粘滞标志y使其匹配

var regEx = /^Zorg/gy;
regExp.lastIndex = 5;
regExp.exec( "What Zorg?" );  // This should match in firefox 
现在是问题。当在不同于0的索引上启动时,是否可以编写在搜索开始时匹配的正则表达式。(目前正在使用节点,但希望在webkit中也能实现此功能)


只需偏移它,因此,{code>/^.{5}Zorg/这意味着“从行首开始的任意5个字符,那么Zorg.

你的意思是
lastIndex
而不是
lastIndes
?是的,我确实更新了这个问题这可能会起作用,但是有可能使regExp表达式独立于索引位置吗?只需从字符串
var regEx=new regExp(^.{lastIndex+“}Zorg”)创建它是的,谢谢,这很有效,但我只是担心如果我在大字符串上执行此操作/^.{2456}Zorg/如果从索引0开始,它将循环通过2456个字符。而不是从索引2456开始。将进行测试。如果愿意,您可以在测试正则表达式之前剪切字符串,但是如果Javascript正则表达式的实现得到了模糊的优化,那么它在速度上不会有太大的差异。在/^[\s\s]{275}Zorg/g和/^[\s\s]{268331}之间没有真正的区别Zorg/g后者甚至比剪切字符串并运行/^Zorg/g慢4-5倍,比运行/Zorg/g并在regexp上设置lastIndex慢5-6倍
var regEx = ????;
regExp.lastIndex = 5;
regExp.exec( "What Zorg?" );  // This this should match 
regExp.exec( "Who is Zorg?" );  // This this should not match