0

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?

4
  • 1
    Either update to Java 8 or do same research. This question is already answered a lot of times. Commented Jan 10, 2016 at 15:43
  • Possible duplicate of Why in Java 8 split sometimes removes empty strings at start of result array? Commented Jan 10, 2016 at 15:43
  • 1
    Why can't you just do a find with \\d? Commented Jan 10, 2016 at 15:43
  • 1
    @cricket_007: I would suggest \\d+ since the numbers can probably be larger than 9. Commented Jan 10, 2016 at 15:44

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.