1

I'm trying to get anything inside {{{#!MyTestMacro and }}} using java regex groups, couldn't get there. Basically I want to remove {{{#!MyTestMacro and }}} which surrounds the content inside it. Below is my code snippet.

File file = new File("mytestfile.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String str1 = new String(data, "UTF-8");

String pattern = "\\{\\{\\{\\s*#!MyTestMacro(.*?)\\}\\}\\}";
Pattern r = Pattern.compile(pattern, Pattern.MULTILINE);
Matcher m = r.matcher(str1);
if (m.find()){
    System.out.println("Found value: " + m.group(0));
    System.out.println("Found value: " + m.group(1));
} else {
    System.out.println("NO MATCH");
}
str1 = str1.replaceAll(pattern, m.group(1));
System.out.println(str1);

Input:

{{{#!MyTestMacro

My desired content.
My desired content2.

}}}

Expected Output:

My desired content. My desired content2.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
Rishi
  • 51
  • 1
  • 3
  • 1
    Replace `Pattern.MULTILINE` with `Pattern.DOTALL` or just add `(?s)` at the beginning of the pattern as `.` does not match line breaks by default. (See [this demo](https://regex101.com/r/2Y9l0w/1)). – Wiktor Stribiżew Aug 29 '18 at 08:32
  • BTW your code doesn't match expected output since `System.out.println("Found value: " + m.group(0));` would print entire match, including `{{{` and `}}}` which doesn't appear in your expected result. – Pshemo Aug 29 '18 at 08:37
  • BTW 2: `str1 = str1.replaceAll(pattern, m.group(1));` will throw exception for `m.group(1)` if scenario where `m.find()` would be `false`. You can use `$1` in replacement part to let `replaceAll` method use match from group 1 (if match for `pattern` will exist) like `str1 = str1.replaceAll(pattern, "$1");`. – Pshemo Aug 29 '18 at 08:41
  • Replace Pattern.MULTILINE with Pattern.DOTALL helped. Thanks! – Rishi Sep 05 '18 at 19:48

0 Answers0