[英]How do I read and remove a number from a 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
值。 说得通?
我能做什么? 如何使我的代码更灵活?
对你起作用吗?
string = string.replaceAll("^\\d+","");
怎么样: -
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("");
}
尝试这个
System.out.println("10yes11no12yes13yes14no".replaceFirst("^\\d+",""));
另一种更具体的尝试:-
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.