Ale*_*ban 4 regex coffeescript
我正在尝试匹配jQuery Mobile URL的哈希片段,如下所示:
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
///
Run Code Online (Sandbox Code Playgroud)
但是,问题是#符号会从编译的JS文件中的正则表达式中删除,因为它被视为注释的开头.我知道我可以切换到正常的正则表达式,但有没有办法在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
///
Run Code Online (Sandbox Code Playgroud)
这将编译到这个正则表达式:
/\#(?:.*\/)?(\w+\.html)$/
Run Code Online (Sandbox Code Playgroud)
和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
///
Run Code Online (Sandbox Code Playgroud)
但是没有多少人会认为\u0023是哈希符号所以\#可能是更好的选择.