1

例如,我有这个字符串:

0no1no2yes3yes4yes

这里的第一个 0 应该被删除并使用数组的索引。我这样做是通过以下声明:

string = string.replaceFirst(dataLine.substring(0, 1), "");

但是,当我说这个字符串时:

10yes11no12yes13yes14no

我的代码失败,因为我想处理 ,10但我的代码只提取1.

所以在排序中,个位数可以正常工作,但两位数或三位数会导致IndexOutOfBound错误。

这是代码: http: //pastebin.com/uspYp1FK

这是一些示例数据: http: //pastebin.com/kTQx5WrJ

这是示例数据的输出:

Enter filename: test.txt
Data before cleanUp: {"assignmentID":"2CCYEPLSP75KTVG8PTFALQES19DXRA","workerID":"AGMJL8K9OMU64","start":1359575990087,"end":"","elapsedTime":"","itemIndex":0,"responses":[{"jokeIndex":0,"response":"no"},{"jokeIndex":1,"response":"no"},{"jokeIndex":2,"response":"yes"},{"jokeIndex":3,"response":"yes"},{"jokeIndex":4,"response":"yes"}],"mturk":"yes"},
Data after cleanUp: 0no1no2yes3yes4yes
Data before cleanUp: {"assignmentID":"2118D8J3VE7W013Z4273QCKAGJOYID","workerID":"A2P0GYVEKGM8HF","start":1359576154789,"end":"","elapsedTime":"","itemIndex":3,"responses":[{"jokeIndex":15,"response":"no"},{"jokeIndex":16,"response":"no"},{"jokeIndex":17,"response":"no"},{"jokeIndex":18,"response":"no"},{"jokeIndex":19,"response":"no"}],"mturk":"yes"},
Data after cleanUp: 15no16no17no18no19no
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.substring(String.java:1907)
    at jokes.main(jokes.java:34)

基本上,代码应该做的是将数据剥离成字符串,如上所示,然后读取数字,如果后面跟着yes增加它的索引值 in dataYes,或者如果后面跟着no增加 in 的值dataNo。说得通?

我能做些什么?如何使我的代码更灵活?

4

4 回答 4

0

对你起作用吗?

string = string.replaceAll("^\\d+","");
于 2013-01-31T13:40:10.730 回答
0

怎么样: -

String regex = "^\\d+";
String myStr = "10abc11def";

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(myStr);

if(m.find())
{
    String digits = m.group();
    myStr = m.replaceFirst("");
}
于 2013-01-31T13:56:18.703 回答
0

试试这个

    System.out.println("10yes11no12yes13yes14no".replaceFirst("^\\d+",""));
于 2013-01-31T14:47:01.300 回答
0

另一种更具体的尝试:-

    String regex = "^(\\d+)(yes|no)";
    String myStr = "10yes11no";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(myStr);

    while (m.find())
    {
        String all = m.group();
        String digits = m.group(1);
        String bool = m.group(2);

        // do not try and combine the next 2 lines ... it doesn't work!
        myStr = myStr.substring(all.length());
        m.reset(myStr);

        System.out.println(String.format("all = %s, digits = %s, bool = %s", all, digits, bool));
    }
于 2013-01-31T15:29:40.527 回答