如何将#作为咖啡脚本heregex的一部分使用?
我试图匹配jQuery移动URL的哈希片段,如下所示:如何将#作为咖啡脚本heregex的一部分使用?,regex,coffeescript,Regex,Coffeescript,我试图匹配jQuery移动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
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
///
然而,问题是#符号在编译的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
///
将编译到此正则表达式:
/\#(?:.*\/)?(\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
识别为哈希符号,因此\\code>可能是更好的选择。这里的实现者。Heregex注释使用简单的正则表达式(/\s+(?:#.*)/g
)与空格一起删除,因此
之前的任何非空格字符(或将其放在最开始处)都有效
是否有一种“官方”方法可以保证一直有效?我(当然)会建议您使用\\\\\\\
并在中简要说明。如前所述,任何与/\s+\\\/
不匹配的序列都有效\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/code>似乎最适合OP案例(我没有列出,因为您已经列出了),但编写例如[?\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\。关于完整和彻底的规范,最好的事情之一就是未来的证明。目前CoffeeScript没有规范或未来的证明。它仍然是一种特别的语言。太好了,这正是我需要的。我看到\#被保留了,但不确定它是否与刚才一样。
$ coffee -bcs
/// [#] ///
/// (?:#) ///
///#///
// Generated by CoffeeScript 1.2.1-pre
/[#]/;
/(?:#)/;
/#/;