Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Regex with RegExp

I'm writing a Regex to detect if a string starts with a valid protocol —lets say for now it can be http or ftp—. The protocol has to be followed by ://, and one or more characters, with no white spaces in the string, ignoring case.

I have this Regex that is doing everything, except checking for white spaces in the string:

const regex = new RegExp('^(http|ftp)(://)((?=[^/])(?=.+))', 'i');
const urlHasProtocol = regex.test(string);
^(http|ftp) — checks for http or ftp at the beginning
(://) — is followed by "://"
((?=[^/])(?=.+)) — is followed by a string that
   (?=[^/]) — doesnt start with "/"
   (?=.+) — has one or more characters

Those must pass:

http://example.com
http://example.com/path1/path2?hello=1&hello=2
http://a
http://abc

Those must fail:

http:/example.com
http://exampl e.com
http:// exampl e.com
http://example.com // Trailing space
http:// example.com
http:///www.example.com

I'm trying to add the rule for the whitespaces. I'm trying with a look ahead that checks for non one or more white spaces in the middle or at the end: (?=[^s+$])

const regex = new RegExp('^(http|ftp)(://)((?=[^/])(?=.+)(?=[^s+$]))', 'i');
const urlHasProtocol = regex.test(string);

But this is not working properly.

Any advice will be welcome

like image 438
Emille C. Avatar asked Mar 15 '21 09:03

Emille C.


2 Answers

With your shown samples only, could you please try following.

^(https?|ftp):\/\/(?!\W*www\.)\S+$

Here is the Online demo of above regex

Explanation: Adding detailed explanation for above regex.

^(https?|ftp):  ##Checking if value starts with http(s optional here to match http/https) OR ftp.
\/\/            ##Matching 2 // here.
(?!\W*www\.)    ##Checking a negative lookahead to see if \W matches any non-word character (equivalent to [^a-zA-Z0-9_]) then www with a dot is NOT in further values.
\S+$            ##matches any non-whitespace character will end of the value here.
like image 155
RavinderSingh13 Avatar answered Sep 19 '22 12:09

RavinderSingh13


Here's my regex for your URL;

I looked for valid URL characters and added them to my Regex

const regex = /^(http|ftp):\/{2}([\w\d]+[-\._~:/?#\[\]@!$&'()*+,;%=]*)*$/i;
const tests = [
  "http://example.com",
  "http://example.com/path1/path2?hello=1&hello=2",
  "http://a",
  "http://abc",
  "http:/example.com",
  "http://exampl e.com",
  "http:// exampl e.com",
  "http://example.com ",
  "http:// example.com",
  "http:///www.example.com"
];

console.log(tests.map(testStr => regex.test(testStr)));
like image 40
a.mola Avatar answered Sep 20 '22 12:09

a.mola