2017-05-07 30 views
1

我有这个字符串中包含“Tulos:+1”多次,我试图找到多少次“Tulos:+1”在该字符串中出现,但它不起作用。无法找到字符串中的模式

它不返回错误。它只是没有找到它。那个吐司只是为了测试。它总是说count2 = 0.顺便说一下,该查询工作正常。

我认为问题是由加号造成的,但我无法弄清楚。

count2 = 0; 

while(query1.moveToNext()){ 

    String str2 = query1.getString(0); 

    Toast.makeText(kortti.this, 
      str2 + count2, Toast.LENGTH_LONG).show(); 

    Pattern p2 = Pattern.compile("Tulos: +1"); 
    Matcher m2 = p2.matcher(str2); 
    while (m2.find()){ 
     count2 +=1; 
     System.out.println(count2); 
    } 

} 
+0

这是加唱......我只是不知道该怎么办。所以正确的方法是编写“Tulos:”+“\\ +”+“1”。我只是不得不添加\\ + – Manutti

回答

0

字符串"Tulos: +1"Tulos:,其次是一个或多个空格字符" ",然后1

如果你想要一个实际的加号,那么你应该逃避它。

"Tulos: \\+1"

+0

是的,我想到了(在评论中),但仍然感谢! – Manutti

0

只是尝试:String.indexOf(字符串str,诠释的fromIndex)具有高性能

int count = 0; 
int start = 0; 
while(true) { 
    int index = str2.indexOf("Tulos: +1", start); 
    if (index < 0) break; 

    start += 9; // 9 is length of "Tulos: +1" 
    count++; 
} 
return count; 
+0

没有必要,但感谢您的评论! – Manutti

+0

顺便说一句,你可以使用'“Tulos:+1”.length()' –