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,144
  • 7
  • 38
  • 48
Liondancer
  • 14,518
  • 43
  • 138
  • 238

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,048
  • 8
  • 36
  • 72
1
for(String current: line.split("\\s+"){
   //do something.
}
Solace
  • 2,151
  • 1
  • 14
  • 32
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,342
  • 4
  • 34
  • 50