[英]Python string parsing url
我有看起來像這樣的字符串:
www.google.com (谷歌網頁) www.facebook.com (Facebook網頁)
或者有些在其中有空格,因為它們在文件夾中:
I:\xyz\text englishtest(英語測試)
I am working with datatables and python flask and want to display the names ( the description in the brackets ) of the url as hyperlink, I have multiple url's in one cell and I got it kind of working but the empty spaces in the url cause problems .
{
"targets": 10,
"data": "download_link",
"render": function (data, type, row, meta) {
var links = data.split(' ');
url = links.shift();
if (links.length) {
links = links.join(' ');
} else {
links = url;
}
console.log('<a href="' + url + '">' + links + '</a>');
return '<a href="' + url + '">' + links + '</a>';
}
}
在您的問題中,您在 javascript 中提供了代碼,所以我的答案基於此。 您的 Python 代碼是任何人的猜測。
您可以使用正則表達式來拆分字符串。 為此,我推薦matchAll
function。
在以下示例中,對包含 url 的幾個部件進行了非常簡化的搜索,並在括號中進行了以下描述。 這兩個部分使用組分開。 可能需要調整正則表達式以更好地滿足您的需求。
const data = [
{
"download_link": "www.google.com (Google Webpage) "
+ "www.facebook.com (Facebook Webpage) "
+ "127.0.0.1:5000/my engishtest (English Test)"
}
];
$(document).ready(function() {
$('#table_id').DataTable({
data: data,
columns: [
{
data: 'download_link',
render: function(data, type, row) {
// The regular expression to search for.
const regexp = /([^\(]+)\(([^\)]+)\)\s*/g;
// Iterate over all search results.
return Array.from(data.matchAll(regexp), m => {
// Extract the found groups and create the URL.
const [_, uri, desc] = m;
return `<a href="${encodeURI('http://' + uri.trim())}">${desc}</a>`;
}).join(' ');
}
}
]
});
});
如果要事先拆分Python中的字符串,我參考re模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.