当从特定位置开始时,将regex匹配到输入的开始

Matching regex to start of input when starting at a specific posistion

本文关键字:输入 开始 regex 定位 位置 开始时      更新时间:2023-09-26

在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的索引开始时匹配搜索的开始。(现在正在使用Node,但希望在webkit中也能实现)

var regEx = ????;
regExp.lastIndex = 5;
regExp.exec( "What Zorg?" );  // This this should match 
regExp.exec( "Who is Zorg?" );  // This this should not match

只是将它偏移,所以/^.{5}Zorg/这意味着'从行开始的任意5个字符,然后是Zorg'。