簡體   English   中英

正則表達式以匹配用空格分隔的數字字符串上的數字

[英]regular expression to match a number on a String of numbers that are separated by spaces

我有一個字符串,例如:

String s = " 10 5 15 55 5 ";

並且我正在嘗試使用regExp獲取數字的重復次數(在本例中為5),因此我的方法如下:

long repetitions = s.split(" 5").length -1;

但這不起作用,它也匹配55。

如果我在數字的兩邊都使用空格,則類似:

String s=" 10 10 15 5 ";
long repetitions = s.split(" 10 ").length -1;

它不起作用,它僅計數10個實例中的一個(我有兩個)。

所以我的問題是哪個regExp可以正確計算兩種情況?

您可以將模式匹配與正則表達式'\\b5\\b'使用,后者使用單詞邊界查找不屬於“其他內容的5 ”:

String s = " 10 5 15 55 5 ";
Pattern p = Pattern.compile("(\\b5\\b)");
Matcher m = p.matcher(s);
int countMatcher = 0;
while (m.find()) { // find the next match
    m.group();
    countMatcher++; // count it
}
System.out.println("Number of matches: " + countMatcher);

輸出值

Number of matches: 2

您可以對10等等執行相同的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM