Velocity Template - regular expressions

2019-02-16 01:34发布

问题:

I just started using velocity for a new job and I really don't like what I have found already. At this point, i would actually prefer freemarker =X. Anyways, i'm trying to do a regular expression and i saw this little bit (search "regular expression"), but that isn't quite the implementation I am doing.

I do not have any access to the java so that option of writing something custom to do this stuff is not there (i'm not even sure if that is possible).

This is what i have right now:

#set ( $envCheck = "(localhost|staging|qa|cms)\\.site" )
#set ( $envCheck = $envCheck.matches($gatewayURL) )

but $envCheck always just comes out as "false". $gatewayURL is defined on the page as well, so that is not the issue.

is this even possible? i was reading that any regexp method that the java String class has is available in the velocity template.

回答1:

Assuming your $gatewayURL is somethign like this:

#set ( $gatewayURL = "localhost.site" )

Then:

#set ( $envCheck = "(localhost|staging|qa|cms)\.site" )
#set ( $envCheck = $gatewayURL.matches($envCheck) )

No need to mask backslash, and you should be calling matches() on gatewayURL, not regular expression.

Velocity doesn't have its own regexp implementation, it just passes parameters you provide to corresponding native java methods, that's all. So you have pretty much full Java SDK at your disposal.



回答2:

This answer is way late but probably still good as a reference for Velocity users encountering the same issue.

We use Velocity 1.5 (too big a task to upgrade to 1.7/1.6 as they broke too many templates) and encountered the same issue. The answer above would not work - backlash without escape (\) results in Lexical error and with escape (\\) return false always as I think it is being interpreted literally. The right way to solve it is by using single quote instead of double quotes when defining the regex expression so Velocity would not attempt to interpret the string that is meant for Java.

#set ( $envCheck = '(localhost|staging|qa|cms)\.site' )
#set ( $envCheck = $envCheck.matches($gatewayURL) )