user1055761
user1055761

Reputation: 1071

Greedy with a trailing greedy Regex in javascript

I am trying to get "a=.*" from the argument list in a URL (http:/a.b.com/?a=123) in Javascript.

/(.*[&|?])(a=.+?)(&.*)/.exec ("http:/a.b.com/?a=123&b=123")

gives me the expected and desired :

["http:/a.b.com/?a=123&b=123", "http:/a.b.com/?", "a=123", "&b=123"]

However, there might not be a following "&arg=val" and I need to be able to search for an optional trailing "&.*" (so adding '?' after the '&' on the third group. Hence :

/(.*[&|?])(a=.+?)(&?.*)/.exec ("http:/a.b.com/?a=123&b=123")

which gives me the unexpected :

["http:/a.b.com/?a=123&b=123", "http:/a.b.com/?", "a=1", "23&b=123"]

The second group now has only 1 character after the '=' and the remainder two '23' are part of the third group..

What I might be doing wrong ? Also any advice to do this a different/better way is also welcomed.

Thanks very much in advance !

Upvotes: 0

Views: 47

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

You have two possibilities:

  • [&?]a=(.+?)(?:&|$)
  • [&?]a=([^&]+)

So, either match non-greedily until you encounter a & or the end of the string, or match greedily all characters except &.

Also, I've shortened your regex and made the group only capture the value of the a parameter, without the a= part. The .* are not needed, your regex doesn't have to match the whole string unless it's anchored with ^ and/or $. And that | in the character class was also wrong.

Example with your test case:

alert(JSON.stringify(
  /[&?]a=([^&]+)/.exec("http:/a.b.com/?a=123&b=123")
))

Upvotes: 1

Related Questions