Java String.split() sometimes giving blank strings

后端 未结 3 1183
一整个雨季
一整个雨季 2020-11-28 15:25

I\'m making a text based dice roller. It takes in strings like \"2d10+5\" and returns a string as a result of the roll(s). My problem is showing up in the tokenizer that spl

3条回答
  •  Happy的楠姐
    2020-11-28 15:38

    I was surprised that it does not happen for case 2 and 3, so the real question here is

    Why is there NO empty string at the start for "d20" and "d%"?

    as Rohit Jain explained in his detailed analyses, this happens, when there is only one match found at the start of the string and the match.end index is 0. (This can only happen, when only a lookaround assertion is used for finding the match).

    The problem is, that d%+3 starts with a char you are splitting on. So your regex matches before the first character and you get an empty string at the start.

    You can add a lookbehind, to ensure that your expression is not matching at the start of the string,so that it is not splitted there:

    String[] tokens = message.split("(?

    (? is a lookbehind assertion that is true, when it is not at the start of the string.

提交回复
热议问题