java - 我正在尝试使用 JAVA 从字符串中获取 URL
问题描述
我正在尝试使用 JAVA 从字符串中获取 URL。但我的变量在“Uri.parse”部分不起作用(变量中没有值)。请考虑我是编码初学者
错误是:“无法为最终变量‘result’赋值”
我的代码:
showResultDialogue(result.getContents());
..
public void showResultDialogue(final String result) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
Pattern p = Pattern.compile("[\\w\\.]+\\.(?:com|cc|net|ru|in)[^,\\s]*");
Matcher m = p.matcher(result);
builder.setTitle("Example Title")
.setMessage("Text is " + result);
if(m.matches()) {
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(result) // here is problem
);
startActivity(browserIntent);
}
});
}
解决方案
由于您没有提供有关它为什么不起作用的信息,我只是假设 URL 丢失http
,因为您的正则表达式不匹配,在这种情况下,我会这样做
编辑:你真的需要你的正则表达式吗?Android 有一种内置的 URL 匹配方式。
你可以在这里找到文档https://developer.android.com/reference/android/util/Patterns
Patterns.WEB_URL.matcher(result).matches();
所以你的代码看起来像这样
if (Patterns.WEB_URL.matcher(result).matches()) {
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(!result.startsWith("http://") && !result.startsWith("https://") ? "http://" + result : result)
);
startActivity(browserIntent);
}
});
}
推荐阅读
- java - 如何在java中对日期进行排序?
- tensorflow - ValueError:没有为任何变量 tensorflow 2.0 提供梯度
- c# - 无法在 Internet Explorer Web 驱动程序中找到更新面板的元素
- python - 两个 pyspark Dataframe 列之间的高效匹配
- java - 如何将对象数组转换为任意内容类型 T (Object[] -> T[])
- c# - How to get migration of Database in c# project
- java - Firebase Messaging Notifications not coming through even though database correctly referenced
- angular - How to get the id of the element who calls a function in the ngif directive?
- coldfusion - cfscript and queryExecute() using like instead of equals
- c# - Unity, setWindowsHook and multi-thread for frame independent input system on Windows