javascript 正規表現 - 代替案の背後を見る? 質問する

javascript 正規表現 - 代替案の背後を見る? 質問する

以下は、ほとんどの正規表現実装で正常に機能する正規表現です。

(?<!filename)\.js$

これは、filename.jsを除いて、.jsで終わる文字列の.jsと一致します。

Javascript には正規表現の後読み機能がありません。同じ結果を達成し、Javascript で動作する代替正規表現を作成できる人はいますか?

ここにいくつかの考えがありますが、ヘルパー関数が必要です。私は正規表現だけでそれを実現することを望んでいました:http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

ベストアンサー1

編集: ECMAScript 2018以降では、後方参照アサーション(無制限も含む)はネイティブにサポートされています

以前のバージョンでは、次の操作を実行できました。

^(?:(?!filename\.js$).)*\.js$

これは、後読み式が暗黙的に行っていることを明示的に実行します。つまり、後読み式とその後の正規表現が一致しないかどうか文字列の各文字をチェックし、一致した場合にのみその文字の一致を許可します。

^                 # Start of string
(?:               # Try to match the following:
 (?!              # First assert that we can't match the following:
  filename\.js    # filename.js 
  $               # and end-of-string
 )                # End of negative lookahead
 .                # Match any character
)*                # Repeat as needed
\.js              # Match .js
$                 # End of string

別の編集:

残念ですが(特にこの回答に多くの賛成票が集まっているので)、この目標を達成するはるかに簡単な方法があります。すべての文字で先読みをチェックする必要はありません。

^(?!.*filename\.js$).*\.js$

同様に動作します:

^                 # Start of string
(?!               # Assert that we can't match the following:
 .*               # any string, 
  filename\.js    # followed by filename.js
  $               # and end-of-string
)                 # End of negative lookahead
.*                # Match any string
\.js              # Match .js
$                 # End of string

おすすめ記事