有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

regex Java文本标准化之间的倒逗号错误

请注意,我花了几天时间试图理解java行为,主要是试图解决以下情况:

我们有以下情况:

I|123|"hi"
U|321|"ola"
D|098|"welcome \n to the hotel \n california"
I|234|"ya!"

作为最终结果,我需要替换“”之间的所有\n,但老实说,我放弃了在“一次性”中执行它,因为我们可以有不同的模式,有时,我们可以在倒逗号中找到“(倒逗号”)。。。像这样" welcome \n to the \"hotel\" \n California".

为了简单、理论上快速地执行,我决定创建一个过程,将最终结果分为几个步骤:

1 - Replace all break lines with special notation;
2 - Replace all remaining break lines with space "";
3 - Replace the special notation, previously inserted, by the original break line! ;

诸如此类:

输入

D|098|"welcome \n to the Hotel \n California"
I|234|"ya!"

步骤:

(Replacing main brake line for special notation)
1 - D|098|"welcome \n to the hotel \california"_¥I|234|"ya!"

(Replacing all brake lines)
2 - D|098|"welcome to the Hotel California"_¥I|234|"ya!"

(Replacing special n)
3 - D|098|"welcome to the Hotel California"
    I|234|"ya!"

问题

我正在使用java和AWS CLI将文件带到内存中并进行处理,然后将其放在文件系统中!在整个过程中,一些处理是采用其中一种,日期标准化,使用相同的技术,目前在这种情况下不起作用

为此,我使用以下代码:

我的故事。replaceAll(“^\n[I|U|D]”,“|U¥”)。“\n(“\n+”)。全部替换(“\n”)

在前面所写的上下文中:

 _¥|123|"hi"
 U|321|"ola"
 D|098|"welcome \n to the hotel \n california"
 I|234|"ya!"

应用此解决方案后,所有文件内容联系人将显示在一行中。所有的线都变成了一次

我真的很感激任何帮助!在这种情况下,“我的错是什么!”

问候!;)


共 (1) 个答案

  1. # 1 楼答案

    您需要删除第一个正则表达式中字符串锚点的^开头,然后捕获\n之后匹配的字母,并在替换模式中使用$1来“恢复”结果中的字符,或者在模式中使用一个不会消耗下一行的IUD字符的前瞻:

    .replaceAll("\n([IUD])", "_¥$1").replaceAll("\n+"," ").replaceAll("_¥","\n")
    .replaceAll("\n(?=[IUD])", "_¥").replaceAll("\n+"," ").replaceAll("_¥","\n")
    

    Java demo

    String s = "I|123|\"hi\"\nU|321|\"ola\"\nD|098|\"welcome \n to the hotel \n california\"\nI|234|\"ya!\"";
    System.out.println(s.replaceAll("\n([IUD])", "_¥$1").replaceAll("\n+"," ").replaceAll("_¥","\n")); 
    

    输出:

    I|123|"hi"
    U|321|"ola"
    D|098|"welcome   to the hotel   california"
    I|234|"ya!"
    

    用双引号之间的空格替换一个或多个换行符的一般解决方案是

    Pattern p = Pattern.compile("\"[^\"]*\"");
    String result = p.matcher(text).replaceAll(x -> x.group().replaceAll("\n+"," "));
    

    this Java demo

    String s = "I|123|\"hi\"\nU|321|\"ola\"\nD|098|\"welcome \n to the hotel \n california\"\nI|234|\"ya!\"";
    Pattern p = Pattern.compile("\"[^\"]*\"");
    s = p.matcher(s).replaceAll(x -> x.group().replaceAll("\n+"," "));
    System.out.println(s);
    

    在Java 9之前,您可以使用Matcher#appendReplacement

    Pattern p = Pattern.compile("\"[^\"]*\"");
    StringBuffer result = new StringBuffer();
    Matcher m = p.matcher(s);
    while (m.find()) {
        m.appendReplacement(result, m.group().replaceAll("\n+", " "));
    }
    m.appendTail(result);
    

    this Java demo