如果找不到匹配项,我的应用会突然停止。这是一段代码:
while (matcher.find()) {
tagValues.add(matcher.group(1));
}
如何向用户显示没有匹配且仍然在同一页面上? 这是logcat。它给出了IndexOutOfBounds异常。
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-16 21:17:56.700: E/AndroidRuntime(19492): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
04-16 21:17:56.700: E/AndroidRuntime(19492): at java.util.ArrayList.get(ArrayList.java:308)
04-16 21:17:56.700: E/AndroidRuntime(19492): at com.approve.smsapp.Conversation$1.onItemClick(Conversation.java:115)
04-16 21:17:56.700: E/AndroidRuntime(19492): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
04-16 21:17:56.700: E/AndroidRuntime(19492): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
04-16 21:17:56.700: E/AndroidRuntime(19492): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
04-16 21:17:56.700: E/AndroidRuntime(19492): at android.widget.AbsListView$3.run(AbsListView.java:3638)
答案 0 :(得分:1)
请添加更多代码以更好地了解您的问题。看下面一个简单的匹配器示例,可能会对您有所帮助:
public class RegexTestPatternMatcher {
public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\w+");
// in case you would like to ignore case sensitivity,
// you could use this statement:
// Pattern pattern = Pattern.compile("\\s+", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
// check all occurance
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
// now create a new pattern and matcher to replace whitespace with tabs
Pattern replace = Pattern.compile("\\s+");
Matcher matcher2 = replace.matcher(EXAMPLE_TEST);
System.out.println(matcher2.replaceAll("\t"));
}
}
答案 1 :(得分:0)
您正在执行matcher.group(1)
,但您的正则表达式并未捕获第一组。因此,要么将group(1)
更改为group(0)
,要么捕获相应的组。
以下是引发java.lang.IndexOutOfBoundsException
例外的示例。
String input = "some input";
Pattern pattern = Pattern.compile(".+");
Matcher m = pattern.matcher(input);
while (m.find()) {
System.out.println(m.group(1));
}
以上案例的解决方案是,
在正则表达式中使用组捕获:
Pattern pattern = Pattern.compile("(.+)");
^ ^ group capture added.
或使用适当的组,例如在这种情况下使用group(0)
System.out.println(m.group(0));