replaceattributessubstringapache-nifi

How to use Expression Language to convert parts of attribute text into upper case


I am trying to update attribute using nifi expression language. I am stuck now. source attribute value is :

"key1"="xXx","key2"="yyy","key3"="zzz"

expected value is

"KEY1"="xXx","KEY2"="yyy","KEY3"="zzz"

I tried this expression:

${src:replaceAll('\"(.+?)\"=',"${'$1':toUpper()}")}

and got syntax error, tried this later:

${src:replaceAll('\"(.+?)\"=',"toUpperCase($1)")}

and got literal "toUpdateCase" into result. it's just not evaluated as a function.

how can I accomplish the goal?


Solution

  • Sadly, you won't be able to achieve this with replaceAll of the NiFi expression language.

    Any EL placed in the replacement value parameter is evaluated before the match is available. In fact, the result of the evaluated expression language is passed to String::replaceAll(String regex, String replacement) which then resolves any group references such as $1. You can see this in the NiFi code.

    A solution to your problem might be to use a ExecuteGroovyScript processor. It's flexible enough for your requirement and you don't need to create a custom processor.

    A Script Body as follows might suffice:

    import org.apache.nifi.flowfile.FlowFile
    
    final String ATTRIBUTE_NAME = "src"
    
    FlowFile flowFile = session.get()
    if (!flowFile) return
    
    final String attributeValue = flowFile.getAttribute(ATTRIBUTE_NAME)
    final String updatedValue = attributeValue.replaceAll("\"(.+?)\"=\"(.+?)\"", { final String[] groups ->
        "\"" + groups[1].toUpperCase() + "\"=\"" + groups[2] + "\""
    })
    
    session.putAttribute(flowFile, ATTRIBUTE_NAME, updatedValue)
    
    session.transfer(flowFile, REL_SUCCESS)