-2

I want to strip '\n' and '\r' characters from a text. I use the following regex: "\\n|\\r" and use string.replaceAll(). This works fine and takes off the \n and \r chars from the string, but it also takes off characters from words starting with 'n' and 'r' with a backslash. eg: someword\new or someword\round --> someowrd\ew, someword\ound. Is there a better way to construct regex ?

sample code: (I use 4 backslashes before 'n' and 'r')

String line_sep_regex = "(\\\\n|\\\\r)";
String finalString = jsonData.toString().replaceAll(line_sep_regex, StringUtils.EMPTY);

Thank you.

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
krb
  • 317
  • 3
  • 8
  • Are you using `\\\\n` or `\\n`? Also why not simply `\n` and `\r`? – Pshemo Oct 20 '17 at 14:16
  • How does text you want to modify look like? – Pshemo Oct 20 '17 at 14:19
  • I use \ \ \ \ n . text is actually json data converted to string. – krb Oct 20 '17 at 14:25
  • So read that JSON data as string, it should get instead of `\n` and `\r` single characters representing line separators. Then remove then using `\r|\n` or `\\R` (available since Java 8 - little more info https://stackoverflow.com/a/31060125/1393766). – Pshemo Oct 20 '17 at 14:28
  • 1
    To post proper answer I would need to see proper [MCVE] (a.k.a. [SSCCE](http://sscce.org)) – Pshemo Oct 20 '17 at 14:37
  • [*Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.* - Jamie Zawinski](http://regex.info/blog/2006-09-15/247) Just use a JSON library like Jackson/GSON and read it in and then convert it back out to a String or file with the line endings you prefer. –  Oct 20 '17 at 14:42
  • 1
    Your question is an [X/Y Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Tell us what problem you are trying to solve instead of asking for help with the solution, which does not appear to be the correct approach. –  Oct 20 '17 at 14:45
  • I would like to remove new line and carriage return characters only without taking out any other string sequence that begins with \r or \n. The regex I use - seems to be taking out words/strings that contain \r or \n – krb Oct 20 '17 at 14:48
  • That is now what Jarrod asked. Why do you want to remove those line separators? What problem are you trying to solve? Anyway manipulating formatted data like JSON structure directly is not best idea. It is better to use proper tool (here JSON parser) which will let us get original data and then work on that data. After that you can format it back to JSON (but still I am not sure if that is what you really want). – Pshemo Oct 20 '17 at 15:01

1 Answers1

-1

Use an anchor in this case $ e.g.

\\r$|\\n$

$ asserts position at the end of the string, or before the line terminator right at the end of the

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107