Search code examples
regextemplatesvelocity

How to extract letter and number sequences from a string in Velocity Template?


I've a string like 'LL101-D10'. I want to extract String before hyphen starting from first numeric digit in Velocity.

Eg - "LL101-D10" , LLL101DL-D10
output - 101 , 101DL

To extract String before hyphen i did as below-

#set ($index = $String.indexOf('-'))
#set ($val1= $String.substring(0, $index))

But How i can extract other part in Velocity? Any help would be appreciated.


Solution

  • You may use a replace operation using the following regex:

    ^[^0-9-]*([0-9][^-]*).*
    

    and replace with the $1 placeholder referring to the contents captured in Group 1.

    See the regex demo

    Details

    • ^ - start of string
    • [^0-9-]* - 0+ chars other than digits and -
    • ([0-9][^-]*) - Group 1: a digit and then 0 or more chars other than -
    • .* - the rest of the string (without linebreaks, if there are line breaks, add (?s) before ^)

    Use it like

    #set ($val1= $String.replaceFirst("^[^0-9-]*([0-9][^-]*).*", "$1"))