开发者

Regex to get grouping of url

If I have a URL contstruct

/SomePart/#/Group1/Group2

I need to return the group1 and/or group2, i.e. the url could be either /SomePart/#/Group1 OR /SomePart/#/Group1/Group2

The current regex I have only gets the first part, not sure how to extend to the latter.

开发者_运维知识库
SomePart\/\#\/([a-zA-Z0-9_-]+)


Do you need to use a regex? Often using a regular expression is overkill. A few lines of code will be faster, and more maintainable than a big regular expression.

If your language has a split method just use that and check the last two items in the generated array.

arr = url.split("/")
if arr[len-2] == "#":
  # There is only one group, so return arr[len-1]
else:
  # Return the last two elements of the array as Group1 and Group2

This pseudo-code is probably a good starting place. In parting, an applicable quote:

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian Kernighan

Save your cleverness for something else :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜