2013-08-19 112 views
0

我有一系列字符串,我正在尋找特定的字符組合。我正在查找一個數字,後跟字母m或M,後跟一個數字數字,然後是字母f或F.Java /正則表達式 - 在字符串中的任意位置查找字符

一個示例字符串是 - 「Class(4)1m5f好」 - 粗體文本是我想要從字符串中提取的內容。

這是我有的代碼,這是行不通的。

Pattern distancePattern = Pattern.compile("\\^[0-9]{1}[m|M]{1}[0-9]{1}[f|F]{1}$\\"); 
Matcher distanceMatcher = distancePattern.matcher(raceDetails.toString()); 
while (distanceMatcher.find()) { 
String word= distanceMatcher.group(0); 
System.out.println(word); 
} 

任何人都可以建議我做錯了什麼?

+4

刪除'^'和'$'... – devnull

+0

也,你不在字符類之後不需要「{1}」。 '[0-9]'本身意味着「一次」。 – mavili

回答

1

我會用字邊界\b

\b\d[mM]\d[fF]\b 

對於Java,反斜線進行轉義:

\\b\\d[mM]\\d[fF]\\b 

{1}是多餘的
[m|M]意味着m|M

+0

需要在Java中跳過斜線(「\\ b \\ d [mM] \\ d [fF] \\ b」),但除此之外,完美無缺。謝謝。 – user2254180

+0

@ user2254180:良好的捕獲,糾正。 – Toto

0

對於r a digit, following by the letter m or M, followed by a digit, then followed by the letter f or F正則表達式的equirement可以簡化爲:

Pattern distancePattern = Pattern.compile("(?i)\\dm\\df"); 

其中:

(?i) - For ignore case 
\\d - For digits [0-9] 
3

在你的正則表達式的開始和結束的^$字符anchors - 他們限制你的字符串,只有由你正在尋找的模式組成。第一步是刪除這些。

然後,您可以使用word boundaries\b)來限制你要找的是一個完整的字,像這樣的格局:

Pattern distancePattern = Pattern.compile("\\b\\d[mM]\\d[fF]\\b"); 

...或者,如果你不介意你圖案出現在一個字的中間,如 「類(4)a1m5f好」,你可以刪除單詞邊界:

Pattern distancePattern = Pattern.compile("\\d[mM]\\d[fF]"); 

快速筆記:

  • 你並不是真的需要{1} s - 默認假設 是一個字符或字符類出現一次。
  • 你可以用 替換[0-9]字符類用\d(這意味着相同的 東西)。
  • 這兩個環節都regular-expressions.info,對學習正則表達式一個很好的資源,我強烈建議你看看:)
+0

神奇的解釋,真的很感激它。 – user2254180

相關問題