0

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
4

1 に答える 1

1

オフセットするだけなので、/^.{5}Zorg/ これは「行頭から任意の 5 文字、次に Zorg」を意味します。

于 2013-03-01T16:45:21.137 に答える