1

I am trying create a basic file system to imitate the terminal. I am currently stuck on getting the names after the command. My first thought was to use regex to parse the commands.

Examples of commands would be:

mkdir hello
ls
cd hello

However to account for many whitespaces an input could be mkdir hello. I was wondering if there is another way without using regex? Also I was curious to which method is faster? With or without regex?

Touchstone
  • 5,575
  • 7
  • 41
  • 48
Liondancer
  • 15,721
  • 51
  • 149
  • 255

3 Answers3

1

You could try splitting the lines like

String[] tokens = line.split(" ");

And for basic commands, most likely your command will be at tokens[0] followed by arguments.

Rey Libutan
  • 5,226
  • 9
  • 42
  • 73
1
for(String current: line.split("\\s+"){
   //do something.
}
Solace
  • 2,161
  • 1
  • 16
  • 33
1

Usually, regex is faster because you can compile it.

see java.util.regex - importance of Pattern.compile()?

(Internally, I think the JVM always compile the regex at some point, but if you do it explicitly, you can reuse it. I am not sure if the JVM is smart enough to reuse a compiled regex locally, maybe it is)

Community
  • 1
  • 1
Leo
  • 6,480
  • 4
  • 37
  • 52