Home > Back-end >  Freemarker - How to split string or keep before certain dynamic substring
Freemarker - How to split string or keep before certain dynamic substring

Time:09-26

I have strings:

apple s/sl/abc
banana a/b/asf
hermit c/d/afd

I want to break two characters before the first "/":

apple
s/sl/ab

banana
a/b/asf

I thought item.item?keep_before("$/") would work for dynamic but need help.

CodePudding user response:

What you meant is ?keep_before("./", "r"). Though you may want to be more specific there, but I don't know the exact syntax of the string that you try to spit.

To get the second half of the string, you could just substring: full[firstHalf?length ..]. Or you can use regular expression look ahead: ?keep_after(r".(?=/)", "r").

?split sadly doesn't work in this use case, because it doesn't support the f (first only) flag, at least as of 2.3.31 (I think it actually should).

CodePudding user response:

In the example you provided could you split on the space? If so, try:

item.item?split(" ")

If not, you might be able to use ?replace and some regex:

item.item?replace(' .*?\/?', ' ', 'r')}

(note the 'r' in the ?replace expression is for regex)

  • Related