Javascript 什么';这个正则表达式怎么了?获取url的哈希部分
我试图从url获取哈希的第一部分(介于#和a/、a?或字符串末尾之间的部分) 到目前为止,我得出了以下结论:Javascript 什么';这个正则表达式怎么了?获取url的哈希部分,javascript,regex,url,hash,Javascript,Regex,Url,Hash,我试图从url获取哈希的第一部分(介于#和a/、a?或字符串末尾之间的部分) 到目前为止,我得出了以下结论: r = /#(.*)[\?|\/|$]/ // OK r.exec('http://localhost/item.html#hash/sub') ["#hash/", "hash"] // OK r.exec('http://localhost/item.html#hash?sub') ["#hash?", "hash"] // WAT? r.exec('http://localh
r = /#(.*)[\?|\/|$]/
// OK
r.exec('http://localhost/item.html#hash/sub')
["#hash/", "hash"]
// OK
r.exec('http://localhost/item.html#hash?sub')
["#hash?", "hash"]
// WAT?
r.exec('http://localhost/item.html#hash')
null
我是为了收到“散列”
我把这个问题查了出来
/#(.*)[$]/
r2.exec('http://localhost/item.html#hash')
null
你知道会出什么问题吗
r = /#(.*)[\?|\/|$]/
当$出现在[]
(字符类)中时,它是文本“$”字符,而不是输入/行的结尾。事实上,您的[\?\/$]
部分仅相当于[?/$]
,它与4个特定字符(包括管道)匹配
改用这个()
除非希望逐字匹配
$
,而不是在行尾匹配,否则不应在字符类中编写[$]
/#(.*)$/
代码:
var regex = /\#(.*)$/;
regex.exec('http://localhost/item.html#hash');
["#hash", "hash"]
输出:
var regex = /\#(.*)$/;
regex.exec('http://localhost/item.html#hash');
["#hash", "hash"]
您的正则表达式:/#(.*)[\?\124;\/|$]/
//-----^ ^-----
|操作员将不在[]内工作,但在()内工作
$将在[]内按字面意思处理
*将尽可能匹配..*?将不贪婪
在作出上述修改后,,
您最终得到的是我用来测试正则表达式的/#(.*?)(\?\/|$)/
。
这里的问题是正则表达式需要一个/
,因此它不能与http://localhost/item.html#hash
但它与http://localhost/item.html#hash/
试试这个:
r = /#([^\?|\/|$]*)/
为什么是正则表达式?这样做(几乎没有正则表达式): 为了方便起见,如果您使用的是
node.js
:
var hash = require('url').parse('http://localhost/item.html#hash').hash;
我发现这个正则表达式似乎有效
r = /#([^\/\?]*)/
r.exec('http://localhost/item.html#hash/sub')
["#hash", "hash"]
r.exec('http://localhost/item.html#hash?sub')
["#hash", "hash"]
r.exec('http://localhost/item.html#hash')
["#hash", "hash"]
无论如何,我仍然不明白为什么原来的一个不起作用。你不能在字符类中使用
$
字符串结束标记。你最好只匹配那些不是/
或?
的字符,如下所示:
/#([^\?\/]*)/
是什么让你如此确信op在浏览器中?没有什么能让我确信,这纯粹是假设。我喜欢玩火。不管怎样,如果没有其他东西可以用的话,我选择Regex作为工具。所以我只是从另一个角度来看待这一点。别忘了我也在尝试在任何“/”或“?”之后去掉这个部分。别忘了我试图忽略过去的部分“/”和“?”@opensas还是更新了。正则表达式与公认答案中的非常相似:)。这与我找到的解决方案完全相同。我发现它非常简单,而且非常优雅。从我收到的评论来看,$将在字符类中进行匹配…是的,你是对的。如果你不想匹配$字符,你应该将其放在[]部分之外。例如:/#([^\?\/]*)$/
/#([^\?\/]*)/