简体   繁体   English

正则表达式匹配以排除开头的单词

[英]Regex matching to exclude beginning word

How can I make the following JavaScript 如何制作以下JavaScript

'id=d41c14fb-1d42&'.match(/(?![id=])(.*)[^&]/)[0]

return "d41c14fb-1d42"? 返回“ d41c14fb-1d42”? It currently returns "41c14fb-1d42", without the beginning "d". 当前返回“ 41c14fb-1d42”,但不以“ d”开头。

This should do it: 应该这样做:

'id=d41c14fb-1d42&'.match(/^id=(.*)&$/)[1]
// "d41c14fb-1d42"

~ edit 〜编辑

When an original question does not give any context it is hard to guess what you need exactly, in which case I just give a solution that yields the requested output. 当原始问题没有给出任何上下文时,很难猜测出您到底需要什么,在这种情况下,我只给出可以产生所请求输出的解决方案。 I now understand you want to be able to parse a query string, ie, name1=value1&name2=value2... . 现在,我了解到您希望能够解析查询字符串,即name1=value1&name2=value2... The following regular expression yields nameX followed by an optional =valueX , as I believe it is valid to provide just the parameter in a query string without a value. 以下正则表达式产生nameX后跟一个可选的=valueX ,因为我相信在查询字符串中仅提供参数而没有值是有效的。

var parameters = "id=foobar&empty&p1=javascript&p2=so".match(/\w+(=([^&]+))?/g)
// ["id=foobar", "empty", "p1=javascript", "p2=so"]

You can split on "=" to obtain parameter and value separately. 您可以分割“ =”以分别获取参数和值。

var param1 = parameters[0].split("=")
// ["id", "foobar"]

For a parameter without the value that would just yield an Array with 1 value, of course. 当然,对于没有该值的参数,只会产生一个值为1的数组。

"empty".split("=") // ["empty"]

Note this assumes a query parameter to match \\w+ , if there are other cases you have to expand the regular expression. 请注意,这假设一个查询参数匹配\\w+ ,如果还有其他情况,则必须扩展正则表达式。

If you only want to match the id parameter specifically anywhere in the query string and obtain its value, as I infer from your comment below, you can use: 如果您只想在查询字符串中的任何地方专门匹配id参数并获取其值(如我从下面的注释中推断的那样),则可以使用:

"id=donald".match(/(?:^|&)id=([^&]+)/)[1]
// "donald"
"param1=value1&id=donald&param2=value2".match(/(?:^|&)id=([^&]+)/)[1]
// "donald"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM