0

I want to simplify this expression a bit. Is there a better way to do this using lookups, or something? I'm pretty junior when it comes to regex. The params $3, $5 and $7 params are optional. $1 is required.

^
/application/
([0-9a-zA-Z_]+)
([\/]([0-9a-zA-Z_]+))?
([/\?|\?|\/]([^\?]*))?
([\?](.*))?
$

service => $1
target  => $3
args    => $5
filter  => $7

/application/blender/banana?add=milk.

btw Im using RegExr to build and test expressions, its a great tool if you havent heard of it.

4

1 回答 1

1

This:

([\/]([0-9a-zA-Z_]+))?

can be simplified to:

(\/[0-9a-zA-Z_]+)?

and:

([\?](.*))?

can be simplified to:

(\?.*)?

because the + and * (and also ?) apply to only the preceding item.

I'm not sure what this:

[/\?|\?|\/]

is supposed to be. Perhaps you mean:

(?:/\?|\?|\/)

i.e. either /? or ? or /. (The (?:...) is a non-capturing group.)

This gives:

^
/application/
([0-9a-zA-Z_]+)
(\/[0-9a-zA-Z_]+)?
((?:/\?|\?|\/)[^?]*)?
(\?.*)?
$

service => $1
target  => $2
args    => $3
filter  => $4
于 2012-01-18T20:03:03.057 回答