2010-07-08 16 views
4

我對正則表達式不太瞭解。
我希望得到以下常規例外的幫助:
1.字符串以字母開頭,然後跟隨任何字母或數字。例如美國廣播公司1月20日至12月15日
2.字符串爲十進制數。例如450,122,224.00
3.還要檢查字符串是否包含任何模式,如'第2頁,共20頁'Java正則表達式

謝謝。

+6

+1「正規例外」 :-) – aioobe 2010-07-08 13:46:55

+2

'string.matches(空)'會給你一個*定期例外*。 – krock 2010-07-08 13:50:16

回答

3
// 1. String start with alpha word and then followed by 
// any aplha or number. e.g. Abc 20 Jan to 15 Dec 

// One or more alpha-characters, followed by a space, 
//  followed by some alpha-numeric character, followed by what ever 
Pattern p = Pattern.compile("\\p{Alpha}+ \\p{Alnum}.*"); 
for (String s : new String[] {"Abc 20 Jan to 15 Dec", "hello world", "123 abc"}) 
    System.out.println(s + " matches: " + p.matcher(s).matches()); 

// 2. String for a decimal number. e.g. 450,122,224.00 
p = Pattern.compile(
     "\\p{Digit}+(\\.\\p{Digit})?|" + // w/o thousand seps. 
     "\\p{Digit}{1,3}(,\\p{Digit}{3})*\\.\\p{Digit}+"); // w/ thousand seps. 
for (String s : new String[] { "450", "122", "224.00", "450,122,224.00", "0.0.3" }) 
    System.out.println(s + " matches: " + p.matcher(s).matches()); 


// 3. Also to check if String contain any pattern like 'Page 2 of 20' 

// "Page" followed by one or more digits, followed by "of" 
// followed by one or more digits. 
p = Pattern.compile("Page \\p{Digit}+ of \\p{Digit}+"); 
for (String s : new String[] {"Page 2 of 20", "Page 2 of X"}) 
    System.out.println(s + " matches: " + p.matcher(s).matches()); 

輸出:

Abc 20 Jan to 15 Dec matches: true 
hello world matches: true 
123 abc matches: false 
450 matches: true 
122 matches: true 
224.00 matches: true 
450,122,224.00 matches: true 
0.0.3 matches: false 
Page 2 of 20 matches: true 
Page 2 of X matches: false 
+0

您的十進制數字匹配器不匹配千位分隔符,例如'450,122,224.00'。 – BalusC 2010-07-08 13:59:53

+0

哦,我認爲這是多個案例...我會更新。 – aioobe 2010-07-08 14:09:38

0

我不確定你在這裏是什麼意思。 te開頭的單詞,後面跟着任意數量的單詞和數字? 試試這個:

^[a-zA-Z]+(\s+([a-zA-Z]+|\d+))+ 

只是一個十進制數將

\d+(\.\d+)? 

獲取逗號有:

\d{1,3}(,\d{3})*(\.\d+)? 

使用

Page \d+ of \d+ 
0

1)/[A-Z][a-z]*(\s([\d]+)|\s([A-Za-z]+))+/

[A-Z][a-z]*是一個大寫字

\s([\d]+)是前綴爲(白色)空間

的數\s([A-Za-z]+)是前綴爲(白色)空間

2.)/(\d{1,3})(,(\d{3}))*(.(\d{2}))/

(\d{1,3})被一個1到3位的數字

(,(\d{3}))*是0或更多的三位數字由前綴字逗號

(.(\d{2}))是一個2位數的小數

3.)/Page (\d+) of (\d+)/

(\d+)是一個或更多的數字

當寫這個(或任何正則表達式),我喜歡用this tool