1

I have a file and i have to read it line by line. The file contains similar lines, like these:

asd@lol kek|1.1.1.1 title@content m e s s a g e|2.3.4.5

I read these lines to String variables. How can i split these strings to other variables? For example: var1=title, var2=content, var3=m e s s a g e, var4=2.3.4.5

I tried something like this, but i cant find the solution:

stringArray=line.split("|");
lacexd
  • 903
  • 1
  • 7
  • 22
  • You need to clearly identify your delimiters. Your desired result even is inconsistent, sometimes the space causes a split and sometimes it doesn't. – Kevin Bowersox Dec 19 '14 at 20:59
  • String has `split` method. Read its documentation and check its overloaded versions (especially `split(regex,limit)`). You can also take a look at `Pattern` and `Matcher` classes. – Pshemo Dec 19 '14 at 21:00
  • 1
    About `split("|")` read [Splitting a Java String by the pipe symbol using split(“|”)](http://stackoverflow.com/questions/10796160/splitting-a-java-string-by-the-pipe-symbol-using-split) – Pshemo Dec 19 '14 at 21:01

1 Answers1

3

You can use this regex for matching and grab the captured groups:

^([^@]+)@(\S+)\s([^|]+)\|(.*)$

RegEx Demo

I suggest you read up a bit on difference between split and match operations.

anubhava
  • 761,203
  • 64
  • 569
  • 643