2

I have this string

Chest pain\tab \tab 72%\tab 0%\tab 67%
 }d \ql \li0\ri0\nowidctlpar\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\tx9360\tx10080\tx10800\tx11520\tx12240\tx12960\faauto\rin0\lin0\itap0 {\insrsid14762702 
 }d \ql \li0\ri0\nowidctlpar\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\tx9360\tx10080\faauto\rin0\lin0\itap0 {\b\f1\fs24\ul\insrsid14762702 Waveform}{\insrsid14762702 
 }{\insrsid14762702 {\*\shppict{\pict{\*\picprop\shplid1025{\sp{\sn shapeType}{\sv 75}}{\sp{\sn fFlipH}{\sv 0}}{\sp{\sn fFlipV}{\sv 0}}{\sp{\sn fLine}{\sv 0}}{\sp{\sn fLayoutInCell}{\sv 1}}}
\

I want to get rid of all lines with }d \ql in them

I have tried

String v= u.replace("}d \\ql(\\.*)","");

but it doesn't detect the line. Having tested it out the culprit must be the .* part but I don't know how to put it in the string.replace

Sebastian Zeki
  • 5,996
  • 7
  • 44
  • 98

1 Answers1

4

replace doesn't use regex syntax, replaceAll does. This means that \\.* simply replace text which represents \ . and *.

So your first solution could look like (notice that to create \ literal in regex you need to escaped it twice: once in regex \\ and once in string literal "\\\\")

String v = u.replaceAll("\\}d \\\\ql.*","");

But possible problem here is that we don't require \} to be placed at start of string. Also we are skipping leading space in that line which exist right before \}.
To solve it we can add ^\s* at start of your regex and make ^ represent start of line (we can do it with MULTILINE flag - we can use (?m) for that).

So now our solution could look like:

String v= u.replaceAll("(?m)^\\s*\\}d \\\\ql.*","");

But there is another problem. . can't match line separators so .* will not include them in match which will prevent us from removing them.
So we should include them in our match explicitly (we should also make them optional - we can use ? quantifier for that - in case line you want to match will be last one, which means it will not have line separator after it). Since Java 8 we can do it with \R which can match few line separators (including paragraph separators), or if you want to limit yourself only to \r \n (or can't use Java 8) you can use something like (\r?\n|\r).

So our final solution can look like:

in Java 8

String v = u.replaceAll("(?m)^\\s*\\}d \\\\ql.*\\R?","");

pre Java 8

String v = u.replaceAll("(?m)^\\s*\\}d \\\\ql.*(\r?\n|\r)?","");
Community
  • 1
  • 1
Pshemo
  • 113,402
  • 22
  • 170
  • 242