2012-02-29 12 views
4

私はこのようなjQueryのモバイルURLのハッシュフラグメントに一致するようにしようとしている。しかし、問題は、それは次のように扱われますので、#記号がコンパイルJSファイル内の正規表現からみじん切りしまうことですCoffeeScript heregexの一部として#を使用する方法?

matches = window.location.hash.match /// 
     #     # we're interested in the hash fragment 
     (?:.*/)?   # the path; the full page path might be /dir/dir/map.html, /map.html or map.html 
          # note the path is not captured 
     (\w+\.html)$  # the name at the end of the string 
     /// 

コメントの開始。私は正規の正規表現に切り替えることができますが、ここで#を使用する方法はありますか?

答えて

5
は、通常の方法でそれをエスケープ

:この正規表現にコンパイルします

matches = window.location.hash.match /// 
    \#     # we're interested in the hash fragment 
    (?:.*/)?   # the path; the full page path might be /dir/dir/map.html, /map.html or map.html 
         # note the path is not captured 
    (\w+\.html)$  # the name at the end of the string 
    /// 

/\#(?:.*\/)?(\w+\.html)$/ 

そして\#は、JavaScriptの正規表現で#と同じです。

また、Unicodeエスケープ\u0023使用することができます

matches = window.location.hash.match /// 
    \u0023    # we're interested in the hash fragment 
    (?:.*/)?   # the path; the full page path might be /dir/dir/map.html, /map.html or map.html 
         # note the path is not captured 
    (\w+\.html)$  # the name at the end of the string 
    /// 

しかし、多くの人々は、ハッシュシンボルとして\u0023を認識しようとしているではないので、\#はおそらくより良い選択です。

+0

偉大な、これは私が必要なものです。私は\#が保持されているのを見ましたが、#と同じことは分かりませんでした。 –

3

ここに実装者があります。 Heregexコメントは、単純な正規表現(/\s+(?:#.*)?/g)を使用して空白で完全に削除されるため、#より前の空白以外の文字(またはそれを最初から置く)は機能します。

$ coffee -bcs 
    /// [#] ///      
    /// (?:#) /// 
    ///#///  

// Generated by CoffeeScript 1.2.1-pre 
/[#]/; 

/(?:#)/; 

/#/; 
+0

いつも働くことが保証されている "公式"なアプローチはありますか?私は(もちろん) '\#'と[ドキュメンテーション](http://coffeescript.org/#regexes)にそれについての簡単なメモを示唆します。 –

+0

説明したように、 '/ \ s +#/'にマッチしないシーケンスがあれば動作します。 '\#'はOPケースに最も適しているようです(あなたがすでに行っているので、私はそれをリストアップしませんでした)。 '[?\#]'は冗長なので、 '[?#]'で十分です。 – matyr

+0

ありがとう、これは知っておくと良いです。 –

関連する問題