简体   繁体   English

通过Java从sql记录中删除新行

[英]Removing new Line from sql record via Java

I am reading and manipulating a MS SQL table using JPA. 我正在阅读和使用JPA处理MS SQL表。 I have text in the cells that I want to cleanup by removing line breaks. 我想通过删除换行符来清除单元格中的文本。 Below is one sample of the text (pasting this in notepad++ shows **CR LF** on each line) : 以下是文本的一个示例(将其粘贴在notepad ++中,每行显示**CR LF** ):

(
(NVSM in (1,2)) and
(NISFVSM in (1,2)) and
(TRMBVSM = 0)
)

I have tried the following code but I can not get rid of the newlines 我已经尝试了以下代码,但无法摆脱换行符

flatTextString.trim()
        .replace(System.getProperty("line.separator"), " ")
        .replaceAll("\t", "")
        .replaceAll("(\\r|\\n)", "")
        .replaceAll("\\s{2,}", " ")
        ;

How can I fix this? 我怎样才能解决这个问题?

I suggest just replacing all newline and carriage returns with just a space, and then remove all whitespace before closing ) and after opening ( : 我建议只是只是一个空间替换所有换行符和回车,然后删除闭幕前的所有空格)并打开后(

String flatTextString = "(\r\n(NVSM in (1,2)) and\r\n(NISFVSM in (1,2)) and\r\n(TRMBVSM = 0)\r\n)";
System.out.println(flatTextString.replaceAll("[\r\n]+", " ").replaceAll("\\s+\\)", ")").replaceAll("\\(\\s+", "(")); // My way
// => ((NVSM in (1,2)) and (NISFVSM in (1,2)) and (TRMBVSM = 0))

See IDEONE demo IDEONE演示

As Java regex cannot use conditional replacement patterns, you can only chain replaceAll methods as I have shown in the code snippet above. 由于Java regex无法使用条件替换模式,因此只能链接上面的代码片段中所示的replaceAll方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM