Digital Mind
Digital Mind

Reputation: 3

Java regex split string into different variables

I have been doing web-scraping for a project and I couldn't figure out how to split retrieved strings into different variables. Array of strings I have retrieved

K. KAYMAKLI TSK 6 5 0 1 19 4 15 15

YEN?CAM? AK 6 4 1 1 14 7 7 13

MORMENEK?E GB 6 4 0 2 10 7 3 12

LEFKE TSK 6 3 2 1 10 8 2 11

SERDARLI GB 6 2 2 2 6 5 1 8

HAM?TKÖY ?HSK 6 2 2 2 8 8 0 8

ÇET?NKAYA TSK 6 2 2 2 6 7 -1 8

DO?AN TBSK 6 2 2 2 12 15 -3 8

YEN? BO?AZ?Ç? DSK 6 2 1 3 9 8 1 7

B. BA?CIL SK 6 1 4 1 8 9 -1 7

MA?USA TÜRK GÜCÜ 6 2 1 3 7 9 -2 7

C?HANG?R GSK 6 1 3 2 8 8 0 6

GENÇL?K GÜCÜ SK 6 1 0 5 6 14 -8 3

YALOVA SK 6 0 2 4 4 18 -14 2

I would like to put the characters until the first integer (in this case 6) into one string and then each integer into separate variables. eg.

String team = "YALOVA SK";
int p = 6;
int x = 0;
int y = 2;
int z = 4;
int m = 4;
int n = 18;
int k = -14;
int h = 2;

I was able to split the string by checking character by character to find the first integer and split it there and then assign each character after that to an integer. How can I solve it by using regex?

Note ?'s are turkish characters that are not displayed correctly on the console but are display correctly in the application.

Upvotes: 0

Views: 1589

Answers (2)

anirudh
anirudh

Reputation: 4176

The split() method on a string can be used to split the string based on a particular 'regex'. For reference on split function check Oracle java documentation link. There is also a nice tutorial about using regex in java in the Vogella website.

You can split the string based on '\s'(short white space character) or '\s+'and then use the returned array.

The syntax will be something like this.

String retrievedString = "YALOVA SK 6 0 2 4 4 18 -14 2";
String[] teamInfo=retrievedString.split("\\s");

You can use the string you retrieve from web scraping in place of "retrievedString".

Note the \\ used in the split method is to escape \.

Hope this helps...

Upvotes: 1

Areo
Areo

Reputation: 938

I think Scanner class fit perfect to your needs: Description: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Upvotes: 0

Related Questions