【问题标题】:llegal escape character followed by a space非法转义字符后跟一个空格
【发布时间】:2012-03-20 21:57:27
【问题描述】:

我正在编写一些代码来使用在终端中加载和运行文件的进程来运行 shell 脚本。我遇到的问题是由于空格而让终端识别文件名,例如:

"$ ./run_file.sh foo bar.ss" 

应该在终端运行

"$ ./run_file.sh foo\ bar.ss"

以下是更改它的代码:

JPanel panel1 = new JPanel();
JButton button = new JButton("Run");
button.setAlignmentX( Component.CENTER_ALIGNMENT);

button.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent event){

        run();

    }

});
//button.setAlignmentX(0.5);
panel1.add(button);
panel1.add(Box.createVerticalGlue());
panel1.add(button);

menuB = new JMenuBar();

JMenu dropD = new JMenu("File");
menuB.add(dropD);

JMenuItem loadR = new JMenuItem("Load file");
JMenuItem quit = new JMenuItem("Quit");
dropD.add(loadR);
dropD.add(quit);
loadR.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event) {
            JFileChooser fileopen = new JFileChooser();

            int r= fileopen.showDialog(panel, "Load file");

            if (r == JFileChooser.APPROVE_OPTION) {
                File file = fileopen.getSelectedFile();
                String string = file.toString();
                string = string.replaceAll(" ", "\ ");
                //String output = aa.replaceAll("/",Character.toString(File.separatorChar));
                System.out.println(string);
                loadFile = file;
        }

       }
  });

我尝试过使用 String.replaceAll 但得到 ​​p>

java:66: illegal escape character

我意识到我可以使用 File.separatorChar :

string = string.replaceAll(" ", Character.toString(File.separatorChar)+" ");

但这似乎并不能取代任何东西...... 任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: java string illegal-characters


    【解决方案1】:

    如果您希望字符串包含 实际的反斜杠,您需要转义反斜杠。否则 javac 认为您正在尝试逃避空间,这不需要转义:

    string = string.replaceAll(" ", "\\ ");
    

    使用此代码,该方法的第二个参数将是一个 2 个字符的字符串:反斜杠后跟空格。我想这就是你想要的。

    有关字符/字符串文字转义序列的更多详细信息,请参阅section 3.10.6 of the Java Language Specification。

    【讨论】:

      【解决方案2】:

      如果要将\ 字符(即转义字符)放入字符串中,则需要对其进行转义:

      string = string.replaceAll (" ", "\\ ");
      

      单个\ 是转义序列前导字符,例如\n(换行符)或\r(回车符)。单字符转义的完整列表是:

      \b    backspace
      \t    tab
      \n    linefeed (newline)
      \f    form feed
      \r    carriage return
      \"    double quote
      \'    single quote
      \\    backslash
      

      这是对八进制转义序列 s 的补充,例如 \0、\12 或 \377。

      您的separatorChar 解决方案不起作用的原因是因为它为您提供了 分隔符 字符(在 UNIX 及其兄弟下为/),而不是您的转义字符 \需要。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-04
        • 1970-01-01
        • 2011-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-14
        相关资源
        最近更新 更多