Reputation: 119
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?
Upvotes: 1
Views: 91
Reputation: 626952
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.
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.
Upvotes: 0
Reputation: 1485
String[] wartosci = line.split("[>\\s]+");
This will split on any sequence of >
and whitespace characters. See documentation of Pattern
Upvotes: 1