Having problems using myString.split(“\n”);

2019-06-15 03:02发布

I need to split an input string into many parts. The splits should occur at "\n" (literally backslash-n, not the newline character). E.g., I want to turn this:

x = [2,0,5,5]\ny = [0,2,4,4]\ndraw y #0000ff\ny = y & x\ndraw y #ff0000

into this:

x = [2,0,5,5]
y = [0,2,4,4]
draw y #0000ff
y = y & x
draw y #ff0000

I would have thought that stringArray = string.split("\n"); would have been sufficient.

But it gives me the same output as input in the following code:

public static void main(String[] args) throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter Input\n");
    String s = br.readLine();
    NewInterpreter interpreter = new NewInterpreter(s);
    interpreter.run();
}

public NewInterpreter(String input) {
    this.input = input;
    this.index = 0;
    this.inputComponents = input.split("\n");
    System.out.println("Output: ");
    for(String s : inputComponents)
        System.out.println(s);
}
Enter Input
x = [2,0,5,5]\ny = [0,2,4,4]\ndraw x #00ff00\ndraw y #0000ff\ny = y & x\ndraw y #ff0000"
Output: 
x = [2,0,5,5]\ny = [0,2,4,4]\ndraw x #00ff00\ndraw y #0000ff\ny = y & x\ndraw y #ff0000

Any help is greatly appreciated, thanks!

2条回答
祖国的老花朵
2楼-- · 2019-06-15 03:21

There can't be any linefeeds in text you read via readLine().

Ergo you must be looking for literal \ followed by a literal n. (Why?)

Ergo you must provide two backslashes for the regular expression compiler, and you will have to escape them both once each for the Java compiler. Total: four.

Alternatively you are just attempting the impossible, trying to split on linefeeds that aren't there. Maybe the input is already split adequately by just calling readLine()?

查看更多
倾城 Initia
3楼-- · 2019-06-15 03:26

If you're entering \n literally (i.e. as opposed to as a newline character), you need to split as follows:

string.split("\\\\n");

The reason for the complexity is that split() takes a regular expression as an argument. When trying to match a literal backslash using a regular expression, it needs to be doubly escaped (once for the regular expression, and once for the string literal).

查看更多
登录 后发表回答