Search code examples
regexfreemarkerdata-processing

How to compare two string in apache free marker


I have below scenario in apache free marker.

str1= Shruti

str2 it can be( "Shruti" ,"shruti", shruti,'Shruti' or SHRUTI)

if string 2 is either with double quote or single quote or plain, we need to return it true. also it should be case insensitive. How can I ignore single quote and double quote in string if it contains and compare?

basically I want to compare 2 strings. if it contains "single quote or double quote" it should ignore. I tried using str1=str2?remove_beginning(""")?remove_end(""") but it is giving error.


Solution

  • You can use replace() and match the quotation marks by escaping them with backslashes \" and \'. I also used trim() to remove leading and trailing spaces and lower_case() to ignore case.
    I tried the following out in the Online FreeMarker Tester

    str1 = "\"Hi\""
    str2 = "'hi'"
    
    <#if str1?trim?replace("\'","")?replace("\"","")?lower_case == str2?trim?replace("\'","")?replace("\"","")?lower_case>
      The two strings are equal
      ${str1?trim?replace("\'","")?replace("\"","")?lower_case} = ${str2?trim?replace("\'","")?replace("\"","")?lower_case}
      
    </#if>
    

    The two strings are equal

    hi = hi


    Here is a function that you can use for comparing two strings.

    <#function is_equal x y>
      <#return x?trim?replace("\'","")?replace("\"","")?lower_case == y?trim?replace("\'","")?replace("\"","")?lower_case>
    </#function>
    
    <#if is_equal(str1,str2)>
      The two strings are equal
    </#if>