JC1
JC1

Reputation: 879

Only catching the first occurrence of a regex string

Currently, I am trying to catch the first occurrence of a 'space' or '->' on each line. However, my expression catches all occurrences of delimiters.

String delimiters = "(->)|[\\s]+"
String[] splittedLine = planArray[i].split(delimiters)

where planArray[i] is the string we're trying to split with regex, e.g. leftClick 100 100

I want leftClick to be splittedLine[0] and 100 100 to be splittedLine[1].

Thanks

Upvotes: 0

Views: 60

Answers (1)

tobias_k
tobias_k

Reputation: 82889

Use the version of split that has a limit parameter and limit the result to 2 parts:

String line = "leftClick 100 100";
String delimiters = "(->)|[\\s]+";
String[] splittedLine = line.split(delimiters, 2);      
System.out.println(Arrays.toString(splittedLine));
// [leftClick, 100 100]

(Also, you could simplify the regex to "->|\\s+".)

Upvotes: 3

Related Questions