3

I'm trying to split a string by a hyphen and a character but unsure of how to use split with Regex. The string is this:

–u tom –p 12345 –h google.com

The hyphen and character are interchangeable in position and how many of them may appear. I'd like them back in an array. Here is what I have so far:

Scanner reader = new Scanner(System.in);
String entireLine = reader.nextLine();
String[] array = entireLine.split("–", -1);

The result I'd like is:

–u tom

–p 12345

–h google.com

Thanks.

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
AzzamAziz
  • 2,144
  • 1
  • 24
  • 34
  • 2
    this is not the best way to parse command line parameters; look into some library like jargs – guido Feb 01 '15 at 22:21
  • I just wanted some a quick thing, HW related. Not concerned with polishing it. Just getting the result. – AzzamAziz Feb 01 '15 at 22:23
  • 1
    what if user input has hyphens: -u peter-p -p pass-word -h my-domain.com http://stackoverflow.com/questions/367706/is-there-a-good-command-line-argument-parser-for-java – Nikita Ignatov Feb 01 '15 at 22:30
  • It won't, we know that ahead of time. – AzzamAziz Feb 01 '15 at 22:33
  • @NikitaIgnatov You would need to incorporate the `space` character in addition to the `dash` character (or `hyphen`). – mrres1 Feb 01 '15 at 22:47
  • possible duplicate of [how to split string with some separator but without removing that separator in Java?](http://stackoverflow.com/questions/4416425/how-to-split-string-with-some-separator-but-without-removing-that-separator-in-j) – Javier Mar 02 '15 at 23:17
  • This question is more regarding the Reggix and less about the Java Split method. – AzzamAziz Mar 03 '15 at 00:27

4 Answers4

6

Try this:

String[] array = entireLine.split("(?<!^)(?=-)");

The negative look behind will prevent splitting at the start of line.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

I would use the following:

String[] array = entireLine.split("\\-", -1);
// or
String[] array = entireLine.split("\\–", -1);

It would give you

u tom

p 12345

h google.com

mrres1
  • 1,147
  • 6
  • 10
1

The split method takes a regular expression in its parameter, so you can use positive lookahead like this

String[] array = entireLine.split("(?=-)");

You have a great explanation of this in a similar question to yours: How to split String with some separator but without removing that separator in Java?

Community
  • 1
  • 1
Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28
0

You can try this:

String[] array = entireLine.split("-*(\\s+)");
Undo
  • 25,519
  • 37
  • 106
  • 129
Mithun
  • 94
  • 4