如何使用 # 作为 CoffeeScript heregex 的一部分? [英] How to use # as part of CoffeeScript heregex?
问题描述
我正在尝试匹配 jQuery Mobile URL 的哈希片段,如下所示:
I'm trying to match the hash fragment of a jQuery Mobile URL like this:
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 中使用 # 吗?
However, the problem is that the # symbol gets chopped from the regex in the compiled JS file because it's treated as the start of a comment. I know I could switch to a normal regex, but is there any way to use # in a 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
///
这将编译成这个正则表达式:
That will compile to this regex:
/#(?:.*/)?(w+.html)$/
并且 #
与 JavaScript 正则表达式中的 #
相同.
And #
is the same as #
in a JavaScript regex.
您也可以使用 Unicode 转义 u0023
:
You could also use the Unicode escape 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
识别为哈希符号,因此 #
可能是更好的选择.
But not many people are going to recognize u0023
as a hash symbol so #
is probably a better choice.
这篇关于如何使用 # 作为 CoffeeScript heregex 的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!