简体   繁体   English

Java正则表达式将字符串拆分为不同的变量

[英]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. 我想将字符直到第一个整数(在这种情况下为6)放入一个字符串中,然后将每个整数放入单独的变量中。 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. 注意 ?是土耳其语字符,不会在控制台上正确显示,但会在应用程序中正确显示。

The split() method on a string can be used to split the string based on a particular 'regex'. 字符串的split()方法可用于基于特定的“正则表达式”对字符串进行拆分。 For reference on split function check Oracle java documentation link. 有关拆分功能的参考,请查看Oracle Java文档链接。 There is also a nice tutorial about using regex in java in the Vogella website . Vogella网站上还有一个很好的教程,关于在Java中使用正则表达式。

You can split the string based on '\\s'(short white space character) or '\\s+'and then use the returned array. 您可以基于'\\ s'(短空格字符)或'\\ s +'分割字符串,然后使用返回的数组。

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". 您可以使用从网络抓取中检索到的字符串代替“ retrievedString”。

Note the \\\\ used in the split method is to escape \\. 请注意,split方法中使用的\\\\是转义\\。

Hope this helps... 希望这可以帮助...

我认为Scanner类非常适合您的需求:说明: http : //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM