![](/img/trans.png)
[英]java.lang.IndexOutOfBoundsException: No group 1 | Pattern matching
[英]group and pattern matching in java
如何使用Matcher和Pattern類來區分此字符串?
我嘗試過這樣
String question="A: this is data i want first B: this is data i want second C: this is data i want third A: this is data i want first B: this is data i want second C: this is data i want third ";
Pattern pattern = Pattern.compile("A:(.*?)B:(.*?)C:(.*?)A:", Pattern.DOTALL | Pattern.MULTILINE);
Matcher m = pattern.matcher(question);
while (m.find()) {
m.group(1);
m.group(2);
m.group(3);
}
這有點hack,但是如果您找不到更好的答案,則可以使用:
使用此正則表達式:
A:(.*?)B:(.*?)C:(.*?)(?=A:)
但是您必須在字符串(您的問題變量)后面添加定界符:
Matcher m = pattern.matcher(question + "A:");
與println一起使用:
while (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
}
它輸出:
這是我首先要的數據
這是我想要的數據
這是我想要的數據第三
這是我首先要的數據
這是我想要的數據
這是我想要的數據第三
由於這需要上下文,因此可以使用ANTLR這樣的解析器,也可以編寫自己的解決方案。
我會喜歡這樣的:
SplitterStringMatcher matcher = new SplitterStringMatcher {
private char delimiter = 'A';
// return the count of characters matched, 0 if none
@Override public int matches(String str, int pos) {
if (str.length() > pos + 1
&& str.charAt(pos) == delimiter
&& str.charAt(pos + 1) == ':') {
if (++delimiter == 'D') { delimiter = 'A'; }
return 2;
}
return 0;
}
}
String[] strs = Splitter.split(question, matcher);
然后實現Splitter
...它必須在每個位置拆分輸入, matches()
返回一個大於0的值,並跳過返回的字符數。
您還可以改進匹配器以在定界符之前和':'
之后匹配空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.