[英]Using Java Pattern Regex to extract information from decoded mailto in WebViewClient
我使用Android API 19将网站嵌入到webview中,在这里我遇到这个问题,即当用户单击链接mailto时。 我想提取信息并启动ACTION_SEND目的。
String firstUrl = "mailto:abc@test.com.kh";
String secondUrl = "mailto:abc@test.com.kh?subject=Request%20to%20create%20a%20new%20listing&body=To%20create%20or%20update%20your%20listing%20on%20cambodiastaging.yoolk.com";
所以我想匹配并获取这样的数据。
email #=> abc@test.com.kh
subject #=> Request%20to%20create%20a%20new%20listing
body #=> To%20create%20or%20update%20your%20listing%20on%20cambodiastaging.yoolk.com
这是我的尝试。
"^mailto:(^?)\\?{0,1}" #=> group1=abc@test.com.kh for both url
我正在寻找的最佳答案是匹配的正则表达式模式:
如果您的secondUrl
始终采用相同的格式(mailto,主题,正文),则可以使用String.split()
三次。
?
先分割secondUrl
并获得第一个元素。 这将是电子邮件ID。 采取上述步骤的第[1]个元素,然后使用&
再次拆分。 现在,第[0]个元素将为subject,另一个元素将为body。
String mailId = secondUrl.split("\\\\?")[0]; String subject = secondUrl.split("\\\\?")[1].split("&")[0]; String body = secondUrl.split("\\\\?")[1].split("&")[1];
不是最好的答案,但对于上面的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更改“主题”和“正文”的顺序或添加更多类似“ cc”的内容,则此正则表达式将中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.