2011-09-01 91 views
0

我制定一個正則表達式,用於驗證包含以下格式的條目文本區域的過程中,Java的正則表達式驗證網址,布爾,字符串

an url, boolean(true or false), string(with or without spaces) 

一個例子如下,

http://www.yahoo.com, true, web mail site 
http://www.google.com, false, a search site 

所以我試圖制定如下每行一個正則表達式,

(^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$)(,(true|false))(,(.*)) 

因此,我可以檢查每一行,但這個正則表達式不起作用。整個正則表達式無法匹配逗號分隔字符串的類型。也有一些方法,我可以使這個正則表達式檢查多行並驗證這種模式?

回答

1

如果換行符是你唯一的問題,你可以使用Pattern.MULTILINE標誌:

Pattern.compile("^((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]), (true|false), (.*)$", Pattern.MULTILINE|Pattern.CASE_INSENSITIVE); 

您也可以嵌入flag(s)

Pattern.compile("(?mi)^((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]), (true|false), (.*)$",); 

我把使用不同的正則表達式的自由爲您的網址(它從Regex Buddy)。這也將把所有東西都放在捕獲組中。


演示:http://ideone.com/I9vpB

public static void extract(String str) { 

    Pattern regex = Pattern.compile("(?mi)^((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]), (true|false), (.*)$"); 

    Matcher m = regex.matcher(str); 
    while (m.find()) { 
     System.out.println("URL: " + m.group(1)); 
     System.out.println("Bool: " + m.group(2)); 
     System.out.println("Text: " + m.group(3) + "\n"); 
    } 
} 

public static void main (String[] args) throws java.lang.Exception 
{ 
    String str = "http://www.yahoo.com, true, web mail site\nhttp://www.google.com, false, a search site"; 
    extract(str); 
} 

輸出:

URL: http://www.yahoo.com 
Bool: true 
Text: web mail site 

URL: http://www.google.com 
Bool: false 
Text: a search site 
+0

多謝你,但是當我試圖通過http://www.cis.upenn.edu測試它/~matuszek/General/RegexTester/regex-tester.html它仍然顯示「模式不匹配」​​:-(不知道如果正則表達式測試儀不能正常工作......我會在實際的代碼中試試這個,看看:)再次感謝。 – Abhishek

+0

@Abhishek查看更新的答案。 – NullUserException