Finding patterns using Regex and replacing them with processed data

There are format input lines

The ENC} {$: 107ec5141234742beec5cb5b1917e2e6 : the ENC {} {$$} the ENC: d0b2ddf0b9e7b397558c20c6232 37c4f: the ENC {} {$$} the ENC: 85d6f3cd7dcc5c67cad68ae45a0d5afc : the ENC {} {$$} the ENC: 5c0dfb55a843f830 024df0d74993b668 : {} $ the ENC

As you can see, the data (in bold) has the prefix $ {ENC}: and the suffix : {ENC} $ . And I want to replace all rows between them with processed data.

I use regex:

\$\{ENC\}\:(.*?)\:\{ENC\}\$

which after escaping for java:

\\$\\{ENC\\}\\:(.*?)\\:\\{ENC\\}\\$

to find matches and replace strings.

My sample code is below:

String THE_REGEX = "\\$\\{ENC\\}\\:(.*?)\\:\\{ENC\\}\\$";
Pattern THE_PATTERN = Pattern.compile(THE_REGEX);

public static boolean isProcessingRequired(String data){
      if(data == null){
          return false;
      }

      return data.matches(THE_REGEX);
}


public String getProcessedString(String dataString){


    Matcher matcher = THE_PATTERN.matcher(dataString);
    if(matcher.matches()){

        String processedData = null;
        String dataItem = matcher.group(1);
        String procItem =  doSomeProcessing(dataItem);

        processedData = dataString.replaceAll("\\$\\{ENC\\}:" + encData + ":\\{ENC\\}\\$", procItem);

        if(isProcessingRequired(processedData)){
            processedData = getProcessedString(processedData);
        }

        return processedData;
    } else {
        return dataString;
    }
}

public String doSomeProcessing(String str){

     // do some processing on the string
     // for now:
       str = "DONE PROCESSING!!"

     return str;

}

But in matcher.group(1)I get

107ec5141234742beec5cb5b1917e2e6:ENC}$${ENC}:d0b2ddf0b9e7b397558c20c623237c4f:{ENC}$${ENC}:85d6f3cd7dcc5c67cad68ae45a0d5afc:{ENC}$${ENC}:5c0dfb55a843f830024df0d74993b668

instead

107ec5141234742beec5cb5b1917e2e6

which I expected.

? , . www.regexe.com, .

enter image description here

?

+4
1

, Matcher.matches() Matcher.find().

javadoc:

public boolean matches()

.


public boolean find()

, .

, :

Matcher matcher = Pattern.compile("\\Q${ENC}\\E(.*?)\\Q{ENC}$\\E").matcher("${ENC}1{ENC}$${ENC}2{ENC}$");

if (matcher.matches()) {
    System.out.println(matcher.group(1)); // Will print "1{ENC}$${ENC}2"
}

matcher.reset();

if (matcher.find()) {
    System.out.println(matcher.group(1)); // Will print "1"
}
+2

All Articles