2014-10-22 68 views
0

我使用android API 19在webview中嵌入網站,在這裏我面對這個問題,當用戶點擊鏈接mailto。我想提取信息並啓動ACTION_SEND意圖。使用Java模式正則表達式從解碼的郵件中提取信息在WebViewClient

String firstUrl = "mailto:[email protected]"; 
String secondUrl = "mailto:[email protected]?subject=Request%20to%20create%20a%20new%20listing&body=To%20create%20or%20update%20your%20listing%20on%20cambodiastaging.yoolk.com"; 

所以我想匹配並獲取這樣的數據。

email #=> [email protected] 
subject #=> Request%20to%20create%20a%20new%20listing 
body  #=> To%20create%20or%20update%20your%20listing%20on%20cambodiastaging.yoolk.com 

這是我的嘗試。

"^mailto:(^?)\\?{0,1}" #=> [email protected] for both url 

最佳答案我要找的是匹配的正則表達式模式:

回答

1

如果您secondUrl總是會以相同的格式(mailto,主題,正文),您可以使用String.split()三次。

  1. 拆分secondUrl先用?得到第一個元素。這將是電子郵件ID。
  2. 取上述步驟的[1]個元素並使用&再次分割。現在,第[0]個元素將是主題,而另一個元素將是主體。

    String mailId = secondUrl.split("\\?")[0]; String subject = secondUrl.split("\\?")[1].split("&")[0]; String body = secondUrl.split("\\?")[1].split("&")[1];

+0

是的,但這不是我尋找的最佳答案。我希望它是靈活的,因爲mailto鏈接是彼此不同的。像「主體」和「身體」的順序。 – 2014-10-22 11:06:10

0

沒有最佳答案,但我得到了現在這個工作對我的URL模式之上。

String mailToRegexp = "^mailto:([^?]+)\\?{0,1}(?:subject=(.+)&body=(.+)){0,1}"; 
Pattern mailToPattern = Pattern.compile(mailToRegexp); 
Matcher mailToMatcher = mailToPattern.matcher(url); 

if (mailToMatcher.find()) { 
    String email = mailToMatcher.group(1); 
    String subject = mailToMatcher.group(2); 
    String body = mailToMatcher.group(3); 

    Intent intent = new Intent(Intent.ACTION_SEND); 
    intent.setType("message/rfc822"); 
    intent.putExtra(Intent.EXTRA_EMAIL, new String[] {email}); 
    if (subject != null) { 
     intent.putExtra(Intent.EXTRA_SUBJECT, URLDecoder.decode(subject)); 
    } 
    if (body != null) { 
     intent.putExtra(Intent.EXTRA_TEXT, URLDecoder.decode(body)); 
    } 

    startActivity(Intent.createChooser(intent, "Email To:")); 
} 

如果模式URL改變「subject」和「body」的順序或者添加更多像「cc」,這個正則表達式將會中斷。

相關問題