如何从字符串中读取和删除数字?

时间:2013-01-31 13:26:34

标签: java string

例如,我有这个字符串:

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,则在dataYes中增加它的索引值,或者no之后dataNo增加值。有意义吗?

我该怎么办?如何使我的代码更灵活?

4 个答案:

答案 0 :(得分:0)

它对你有用吗?

string = string.replaceAll("^\\d+","");

答案 1 :(得分: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("");
}

答案 2 :(得分:0)

试试这个

    System.out.println("10yes11no12yes13yes14no".replaceFirst("^\\d+",""));

答案 3 :(得分: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));
    }