Regex Обнаруживает URL-адреса и делает ссылку <a> - PullRequest
0 голосов
/ 28 мая 2020

У меня есть регулярное выражение, и я пытаюсь найти все URL-адреса для создания ссылки (), но у меня следующие проблемы:

  • Некоторые URL-адреса с "\ foo \ bar" не получают их
  • URL принимает его как часть Интернета.

www.foo.com -> https://mywebsite.com/section/www.foo.com

возможно, что если это ссылка без https, она будет помещена автоматически (избегая ftp, \ hostname или \ ip) ???

Спасибо!

Live Regex: https://regex101.com/r/w3o9w1/1

Регулярное выражение:

/(?:(?:https?|ftp|):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?/gm

Текстовая демонстрация:

text www.example.com  text text text http://example.com 

\\hadgs01\test2
http://192.168.1.1:3000/
192.168.1.1:3000
\\192.168.10.10\test\test.txt

http://example.com
http://example.gl
http://www.example.com
https://example.com
https://www.example.com
https://www.example.com/
https://www.example.com/bar
https://example.com/icons?d=bar&q=bar
http://abc.dec.ed.example.com
http://example.gl/1 http://example.gl/2
foo (http://example.gl/1) http://example.gl/(2)
http://example.com/. http://example.com/! http://example.com/,
example.gl/1
http://example.com/review/abc-def-ghi/?ct=t(test_test_bar)


www.example.com.au
http://www.example.com.au
http://www.example.com.au/ersdfs
http://www.example.com.au/bar?dfd=test@s=1
http://www.example.com:81/bar.html

Код:

 var regex_links = /(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?/gm;

$(".text_to_replace").html($(".text_to_replace").html().replace(regex_links, " <a href=\"$&\" target='_blank'>$&</a> "));

1 Ответ

1 голос
/ 28 мая 2020

Ваше регулярное выражение довольно близко к вашим ожиданиям; но для соответствия строк вашим требованиям ( соответствие "\\ hadgs01 \ test2" или "\\ 192.168.10.10 \ test \ test.txt" ) вы можете использовать следующее регулярное выражение:

(?:(https?|ftp)?:?\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?

Изменения, внесенные в ваше регулярное выражение:

(?:https?|ftp|): изменено на (https?|ftp|)?:? - Я внес следующие изменения в ваше регулярное выражение, чтобы захватить группу для вашего второго требования, а также сопоставить нужные строки типов \\hadgs01\test2 и \\192.168.10.10\test\test.txt.

РЕАЛИЗАЦИЯ В JAVASCRIPT:

const myRegexp = /(?:(https?|ftp)?:?\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?/gm;
const myString = `
text www.example.com  text text text http://example.com 
//hadgs01/test2
http://192.168.1.1:3000/
192.168.1.1:3000
\\\\192.168.10.10\\test\\test.txt

http://example.com
http://examp.ele
http://www.example.com
https://example.com
https://www.example.com
https://www.example.com/
https://www.example.com/bar
https://example.com/icons?d=bar&q=bar
http://abc.dec.ed.example.com
http://examp.le/1 http://examp.ele/2
foo (http://examp.ele/1) http://examp.ele/(2)
http://example.com/. http://example.com/! http://example.com/,
examp.le/1
http://example.com/review/abc-def-ghi/?ct=t(test_test_bar)
www.example.com.au
http://www.example.com.au
http://www.example.com.au/ersdfs
http://www.example.com.au/bar?dfd=test@s=1
http://www.example.com:81/bar.html
\\ example \\\\
`;

// PLEASE NOTE I REPLACED FOO and goo.gle from the string to example and examp.ele because of the norms
let match;
// Taken the below variable to store the result
let resultString = "";
match = myRegexp.exec(myString);
while (match != null) {
// If group 1 of match is null that means it does'nt contain anything among https, http or ftp but it match rest of the requirement.
  if(match[1] == null)
  // If in case the link already contains slashes like //hadgs01/test2
    if(match[0].includes('//'))
      resultString = resultString.concat("https:" + match[0] + "\n");
    else
      resultString = resultString.concat("https://" + match[0] + "\n");
  else
    resultString = resultString.concat(match[0] + "\n");
  
  match = myRegexp.exec(myString);
}
console.log(resultString);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...