Using velocity split() to split a string into an array doesnt seem to work

前端 未结 5 1734
猫巷女王i
猫巷女王i 2021-01-11 12:17

I HATE velocity and rarely ever use it but sometimes I am called upon at my job to do so. I can never really figure out just how to use it.

I have this



        
相关标签:
5条回答
  • 2021-01-11 12:56
    ## Splitting by Pipes
    #set($prodId = $product.productId)
    #foreach($id in $prodId.split("[|]"))
    $id
    #end
    
    0 讨论(0)
  • 2021-01-11 12:57

    Spilt string in vtl script::

    foreach($subString in $yourString.split(','))

    { "$subString " } #if($foreach.hasNext),#end

    endenter code here

    0 讨论(0)
  • 2021-01-11 12:57

    Apparently even though the velocity documentation says that the delimiter is a string it's really a regular expression. Thanks apache.

    proper way is

    $product.product.split("\|");
    
    0 讨论(0)
  • 2021-01-11 12:58

    Without using StringUtils this can be done using the String split() method.

    Unlike it's Java counterpart for special characters one doesn't need to escape the forward slash (.e.g "\\|") as @kamcknig correctly stated:

    #set ($myString = “This|is|my|dummy|text”) 
    
    #set ($myArray = $myString.split("\|")) or
    #set ($myArray = $myString.split('\|')) or
    #set ($myArray = $myString.split("[|]"))
    

    Note 1: To get the size of the array use: $myArray.size()

    Note 2: To get actual values use $myArray.get(0) or $myArray[0] … etc

    Suggestion: one could use beforehand #if ($myString.indexOf(‘|’)) ... #end

    0 讨论(0)
  • 2021-01-11 12:59

    Velocity has extremely few objects and methods of its own. Instead, it allows you to work with real Java objects and call real Java methods on those objects. Which Velocity documentation says that the delimiter is a string?

    Moreover, since Velocity is Java-based, a string is just a data type that can hold many types of information: phone numbers, names, identifiers, regular expressions... In Java, many methods dealing with regular expressions pass those REs as String objects.

    You can check the actual type that a value behind a variable has by printing its classname:

    Product class is $product.class
    Product ID class is $product.productId.class
    

    If the product ID is indeed a java.lang.String, then you can check that the split method takes a String parameter, but that String is expected to be a valid regular expression.

    And since | is a special character in regular expressions, you need to escape it somehow. This works:

    #foreach( $stringList in $product.productId.split("[|]") )
    
    0 讨论(0)
提交回复
热议问题