java正則表達式匹配計數假設我有一個文件,該文件包含:HelloxxxHelloxxxHello我編譯一個模式來尋找'你好'Pattern pattern = Pattern.compile("Hello");然后我使用輸入流來讀取文件并將其轉換為String,以便可以對其進行重新編碼。一旦匹配器在文件中找到匹配項,它就表明了這一點,但它沒有告訴我它找到了多少匹配項; 只是它在String中找到了一個匹配項。因此,由于字符串相對較短,并且我使用的緩沖區是200字節,因此它應該找到三個匹配項。但是,它只是簡單地說匹配,并沒有向我提供有多少匹配的計數。計算String中發生的匹配數的最簡單方法是什么。我已經嘗試了各種for循環并使用matcher.groupCount(),但我無處可去。
3 回答

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
matcher.find()
沒有找到所有的比賽,只有下一場比賽。
你必須做以下事情:
int count = 0;while (matcher.find()) count++;
順便說一句,matcher.groupCount()
是完全不同的東西。
完整的例子:
import java.util.regex.*;class Test { public static void main(String[] args) { String hello = "HelloxxxHelloxxxHello"; Pattern pattern = Pattern.compile("Hello"); Matcher matcher = pattern.matcher(hello); int count = 0; while (matcher.find()) count++; System.out.println(count); // prints 3 }}
處理重疊匹配
當計算上述片段aa
中aaaa
的匹配時,您將獲得2。
aaaa aa aa
要獲得3個匹配,即此行為:
aaaa aa aa aa
您必須在索引中搜索匹配,<start of last match> + 1
如下所示:
String hello = "aaaa";Pattern pattern = Pattern.compile("aa");Matcher matcher = pattern.matcher(hello);int count = 0;int i = 0;while (matcher.find(i)) { count++; i = matcher.start() + 1;}System.out.println(count); // prints 3

幕布斯7119047
TA貢獻1794條經驗 獲得超8個贊
這適用于可能重疊的匹配:
public static void main(String[] args) { String input = "aaaaaaaa"; String regex = "aa"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); int from = 0; int count = 0; while(matcher.find(from)) { count++; from = matcher.start() + 1; } System.out.println(count);}
添加回答
舉報
0/150
提交
取消