解析包含多个符号的字符串会导致崩溃

时间:2017-03-24 15:13:56

标签: java regex algorithm string-parsing

我试图在Java中拆分包含","":""-"

的某些字符

例如,

如果输入为58,1:2-4,则应生成以下输出

  1. 图书编号:58
  2. 章节编号:1
  3. Verses = [2,3,4](因为2-4是 值从2到4)
  4. 以下是我尝试过的代码,

    private int getBookNumber() {
            bookNumber = chapterNumber.split("[,]")[0];
            return Integer.valueOf(bookNumber);
        }
    
        private int getChapterNumber() {
            chapterNumber = sample.split("[:]")[0];
            verseNumbers = sample.split("[:]")[1];
            return Integer.valueOf(chapterNumber);
        }
    
        private List<Integer> getVerseNumbers(String bookValue) {
            List<Integer> verseNumList = new ArrayList<>();
            if (bookValue.contains("-")) {
                //TODO parse - separated string
            } else {
                verseNumList.add(Integer.valueOf(bookValue));
            }
    
            return verseNumList;
        }
    

    我会按顺序以下列方式调用它们

    int chapterNumber = getChapterNumber(); 
    int  bookNumber    = getBookNumber();
    List<Integer> verseNumbers  = getVerseNumbers(this.verseNumbers);
    

    但是我得到了引起:java.lang.NumberFormatException:行int chapterNumber = getChapterNumber();

    中的int:“58,1”无效

    是否有一种解析此字符串的有效方法?

2 个答案:

答案 0 :(得分:2)

您应该像这样更改getChapterNumber:

private int getChapterNumber() {
    chapterNumber = sample.split("[:]")[0];
    verseNumbers = sample.split("[:]")[1];
    return Integer.valueOf(chapterNumber.split("[,]")[1]);
}

但最好的方法是使用匹配器:

String line = "58,1:2-4";
Pattern pattern = Pattern.compile("(\\d+),(\\d+):(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 2: " + matcher.group(2));
    System.out.println("group 3: " + matcher.group(3));
}

输出:

group 1: 58
group 2: 1
group 3: 2-4

答案 1 :(得分:1)

我可能会使用基本字符串方法来避免使用正则表达式匹配器附带的重型设备:

String input = "58,1:2-4";
int commaIndex = input.indexOf(",");
int colonIndex = input.indexOf(":");
int bookNumber = Integer.valueOf(input.substring(0, commaIndex));
int chapterNumber = Integer.valueOf(input.substring(commaIndex+1, colonIndex));
String verseString = input.substring(colonIndex+1);
String[] verses = verseString.split("-");
int startVerse = Integer.valueOf(verses[0]);
int endVerse = Integer.valueOf(verses[1]);
int[] allVerses = new int[endVerse - startVerse + 1];
for (int i=0; i < allVerses.length; ++i) {
    allVerses[i] = startVerse + i;
}