简体   繁体   中英

How to split line using regular expression

I need to create regular expression which will split first line from file like this:

Array[0] = 0 
Array[1] = 2
Array[2] = 3

Here is a example of this file

0 > 2 3
2 > 0 2
0 > 1 1
1 > 2 4

I tried doing this and it worked without blank characters like this 0>2 3 but I heard from my teacher that space between > is necessary.

My regular expression:

String[] wartosci = line.split(">|\\s");

How to do that?

String[] wartosci = line.split("[>\\s]+");

This will split on any sequence of > and whitespace characters. See documentation of Pattern

I think you need to split on any non-digit. So, use

String results[] = s.split("\\D+");

See the IDEONE demo

Here, \\D+ matches 1 or more non-digit characters.

Java demo :

String s = "0 > 2 3";
String results[] = s.split("\\D+");
System.out.println(Arrays.toString(results));
// => [0, 2, 3]

Note that Avinash's [>\\\\s]+ is a whitelist approach, and if you plan to follow it, you might need to expand the character class with other symbols (like < , = , or even - ...

And a couple of words about performance: your >|\\\\s regex is using one symbol alternation that is much less efficient that a character class [>\\\\s] that invloves much less backtracking (since it is compiled into 1 "entity" in the "regex internal program"). Whenever you wanted to match 1 symbol from a set of characters, use a character class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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