I'm trying to get the digits from the expression [1..1]
, using Java's split
method. I'm using the regex expression ^\\[|\\.{2}|\\]$
inside split
. But the split
method returning me String array with first value as empty, and then "1" inside index 1 and 2 respectively. Could anyone please tell me what's wrong I'm doing in this regex expression, so that I only get the digits in the returned String array from split
method?

- 2,191
- 6
- 38
- 57
-
1Either update to Java 8 or [do same research](https://www.google.de/search?q=java+split+first+empty). This question is already answered a lot of times. – Tom Jan 10 '16 at 15:43
-
Possible duplicate of [Why in Java 8 split sometimes removes empty strings at start of result array?](http://stackoverflow.com/questions/22718744/why-in-java-8-split-sometimes-removes-empty-strings-at-start-of-result-array) – A4L Jan 10 '16 at 15:43
-
1Why can't you just do a find with `\\d`? – OneCricketeer Jan 10 '16 at 15:43
-
1@cricket_007: I would suggest `\\d+` since the numbers can probably be larger than `9`. – Willem Van Onsem Jan 10 '16 at 15:44
4 Answers
You should use matching. Change your expression to:
`^\[(.*?)\.\.(.*)\]$`
And get your results from the two captured groups.
As for why split
acts this way, it's simple: you asked it to split on the [
character, but there's still an "empty string" between the start of the string and the first [
character.

- 50,214
- 11
- 107
- 158
Your regex is matching [
and ..
and ]
. Thus it will split at this occurrences.
You should not use a split but match each number in your string using regex.

- 2,144
- 1
- 19
- 25
You've set it up such that [
, ]
and ..
are delimiters. Split
will return an empty first index because the first character in your string [1..1]
is a delimiter. I would strip delimiters from the front and end of your string, as suggested here.
So, something like
input.replaceFirst("^[", "").split("^\\[|\\.{2}|\\]$");
Or, use regex and regex groups (such as the other answers in this question) more directly rather than through split.
Why not use a regex to capture the numbers? This will be more effective less error prone. In that case the regex looks like:
^\[(\d+)\.{2}(\d+)\]$
And you can capture them with:
Pattern pat = Pattern.compile("^\\[(\\d+)\\.{2}(\\d+)\\]$");
Matcher matcher = pattern.matcher(text);
if(matcher.find()) { //we've found a match
int range_from = Integer.parseInt(matcher.group(1));
int range_to = Integer.parseInt(matcher.group(2));
}
with range_from
and range_to
the integers you can no work with.
The advantage is that the pattern will fail on strings that make not much sense like ..3[4
, etc.

- 443,496
- 30
- 428
- 555