我正在尝试获得一个可选的前瞻性,但是当我将其设为可选(在其后添加 ?
)时遇到问题,即使数据存在,它也不再匹配。
作为一个简短的总结,我正在尝试从 URI 中提取特定的查询字符串参数。示例:
/.*foo.html\??(?=.*foo=([^\&]+))(?=.*bar=([^\&]+))/
.exec( 'foo.html?foo=true&bar=baz' )
我会稍微分解一下:
.*foo.html\?? // filename == `foo.html` + '?'
(?=.*foo=([^\&]+)) // find "foo=...." parameter, store the value
(?=.*bar=([^\&]+)) // find "bar=...." parameter, store the value
以上示例在 foo
和 bar
作为参数存在于查询字符串中的情况下完美运行。问题是我试图使这些成为可选的,所以我将其更改为:
/.*foo.html\??(?=.*foo=([^\&]+))?(?=.*bar=([^\&]+))?/
↑ ↑
Added these question marks ─┴──────────────────┘
它不再匹配任何参数,尽管它仍然匹配 foo.html
。有什么想法吗?
最佳答案
尝试将问号放入 look-ahead 中:
...((?=(?:.*foo=([^\&]+))?)...
看起来很奇怪,但我认为漂亮的正则表达式不是目标:-)
还有,你有没有想过这个?
/.*foo.html\??.*(?:foo|bar)=([^\&]+).*(?:bar|foo)=([^\&]+)/
关于javascript - 可选的正则表达式前瞻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9012729/