Regex for URLs and files


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Regex for URLs and files
# 1  
Old 09-28-2016
Regex for URLs and files

Hi,

I am looking for a regex that will validate a URL and files accessed in a browser.

For example:
Code:
http://www.google.co.uk
http://www.google.com
https://www.google.co.uk
https://www.google.com
ftp://
file:///somefile/on/a/server/accessed/from/browser/file.txt

So far I have:

Code:
/^(?:(?:https?|ftp|http):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i

but this only checks for http, https, ftp

How can I get it to also validate files:
Code:
file://c:/a/b/c.txt
file:///some/file/on/a/unix/a.txt

SmilieSmilieSmilie

Thanks

Moderator's Comments:
Mod Comment
Please wrap all code, files, input & output/errors in CODE tags.
It makes it far easier to read, does not convert text into URLs or email address and preserves spacing for indenting or fixed width data.

Last edited by rbatte1; 09-28-2016 at 11:23 AM.. Reason: Added CODE tags for input
# 2  
Old 09-28-2016
Hello muay_tb,

I have tidied up your post with CODE tags are removed the URL formatted that hid most of it from view. Please wrap all code, files, input & output/errors in CODE tags. It makes it far easier to read, does not convert text into URLs or email address and preserves spacing for indenting or fixed width data. Highlight the text and press the toll-button with co over de in it.


On your question, perhaps it would be better to explain more simply what you are going to match against. Is the expression to match these specific cases? If so, you might be better with an extended regular expression of
first string|second string|third string|.... ... etc.

Do you have some sample input that we can consider matching against?



I'm still at a loss as to your eventual aim though.


Kind regards,
Robin
# 3  
Old 09-28-2016
Hi.

If you are comfortable using perl and associated library modules:
Code:
NAME
    Regexp::Common::URI -- provide patterns for URIs.

SYNOPSIS
        use Regexp::Common qw /URI/;

        while (<>) {
            /$RE{URI}{HTTP}/       and  print "Contains an HTTP URI.\n";
        }

DESCRIPTION
    Patterns for the following URIs are supported: fax, file, FTP, gopher,
    HTTP, news, NTTP, pop, prospero, tel, telnet, tv and WAIS. Each is
    documented in the Regexp::Common::URI::scheme, manual page, for the
    appropriate scheme (in lowercase), except for NNTP URIs which are found in
    Regexp::Common::URI::news.

excerpt from perldoc Regexp::Common::URI , q.v

Best wishes ... cheers, drl
# 4  
Old 09-29-2016
Hi,

Thanks for your replies.

I am trying to validate URLS entered.

They all will have a protocol such as http://, https://, ftp://.

I also want to ensure that URLs that are files such as file:///somefile/a.txt is also validated.

Examples could be:

Code:
http://www.google.com
https://www.google.com
ftp://server.com/file/a.txt
file:///some/path/to/file.txt


Hope this helps?Smilie
# 5  
Old 09-29-2016
Hi.

Here is a sample of perl validation, driven by a shell script:
Code:
#!/usr/bin/env bash

# @(#) s1       Demonstrate URI validation with perl module.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
em() { pe "$*" >&2 ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C perl

FILE=${1-data1}

pl " Sample perl code, callable at command line:"
cat p1

pl " Input data file $FILE:"
cat $FILE

pl " Results:"
./p1 data1

exit 0

producing:
Code:
$ ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.6 (jessie) 
bash GNU bash 4.3.30
perl 5.20.2

-----
 Sample perl code, callable at command line:
#!/usr/bin/env perl

# @(#) p1       Demonstrate URI validation module.

use strict;
use warnings;
use Regexp::Common qw /URI/;

# Extended pattern to match HTTPS.
my($https) = qr($RE{URI}{HTTP}{-scheme=>qr/https/});

# Convert to lowercase for match, but retain original for display.
my($uri);
while (<>) {
  chomp;
  $uri = $_;
  $_ = lc;
  /$https/ and print "Contains an HTTPS URI: $uri\n";
  /$RE{URI}{HTTP}/ and print "Contains an HTTP URI: $uri\n";
  /$RE{URI}{file}/ and print "Contains a  FILE URI: $uri\n";
  /$RE{URI}{FTP}/ and print "Contains an FTP URI: $uri\n";
}

exit(0);

-----
 Input data file data1:
http://www.google.com
https://www.google.com
http
HTTP
ftp://server.com/file/a.txt
faux://bad
file:///some/path/to/file.txt
phonehome://///something
helloworld://www.unix.com
https://www.unix.com
https://www.unix.com
https://www.unix.com/shell-programming-and-scripting/268589-regex-urls-files.html

-----
 Results:
Contains an HTTP URI: http://www.google.com
Contains an HTTPS URI: https://www.google.com
Contains an FTP URI: ftp://server.com/file/a.txt
Contains a  FILE URI: file:///some/path/to/file.txt
Contains an HTTP URI: https://www.unix.com
Contains an HTTP URI: https://www.unix.com
Contains an HTTP URI: https://www.unix.com/shell-programming-and-scripting/268589-regex-urls-files.html

Some of this is fairly complicated, so if you or friends do not wish to tackle it, perhaps someone will drop in with a better solution.

Best wishes ... cheers, drl
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Sendmail K command regex: adding exclusion/negative lookahead to regex -a@MATCH

I'm trying to get some exclusions into our sendmail regular expression for the K command. The following configuration & regex works: LOCAL_CONFIG # Kcheckaddress regex -a@MATCH +<@+?\.++?\.(us|info|to|br|bid|cn|ru) LOCAL_RULESETS SLocal_check_mail # check address against various regex... (0 Replies)
Discussion started by: RobbieTheK
0 Replies

2. Programming

Python Reading Individual files and Regex through them

As a newbie to Python, I am trying to write a script in which is will add all the log files (*.log) from within a directory to a list, open the files and search for an ip using a regex and single it out (appending the ip's to the list). So far, I have: import re, os def list_files() content = ... (4 Replies)
Discussion started by: metallica1973
4 Replies

3. Shell Programming and Scripting

Hashing URLs

So, I am writing a script that will read output from Bulk Extractor (which gathers data based on regular expressions). My script then reads the column that has the URL found, hashes it with MD5, then outputs the URL and hash to a file. Where I am stuck on is that I want to read the bulk... (7 Replies)
Discussion started by: twjolson
7 Replies

4. Shell Programming and Scripting

How to remove urls from html files

Does anybody know how to remove all urls from html files? all urls are links with anchor texts in the form of <a href="http://www.anydomain.com">ANCHOR</a> they may start with www or not. Goal is to delete all urls and keep the ANCHOR text and if possible to change tags around anchor to... (2 Replies)
Discussion started by: georgi58
2 Replies

5. UNIX for Dummies Questions & Answers

awk to match multiple regex and create separate output files

Howdy Folks, I have a list that looks like this: (file2.txt) AAA BBB CCC DDD and there are 24 of these short words. I am matching these patterns to another file with 755795 lines (file1.txt). I have this code for matching: awk -v f2=file2.txt ' BEGIN { while(... (2 Replies)
Discussion started by: heecha
2 Replies

6. Shell Programming and Scripting

Converting perl regex to sed regex

I am having trouble parsing rpm filenames in a shell script.. I found a snippet of perl code that will perform the task but I really don't have time to rewrite the entire script in perl. I cannot for the life of me convert this code into something sed-friendly: if ($rpm =~ /(*)-(*)-(*)\.(.*)/)... (1 Reply)
Discussion started by: suntzu
1 Replies

7. Shell Programming and Scripting

multiple regex finding in files

Hello folks, I have a text file aa.txt that contains below text (\')|(\-\-) ((\%3D)|(=)) 20%0d% i want to search each line pattern in /opt/1.log and /opt/2.log. Can some one suggest (1 Reply)
Discussion started by: learnbash
1 Replies

8. UNIX for Advanced & Expert Users

find: search regex of files?

I want to use the find command to search a ton of files, but I want to break it up into multiple machines. I want to search for files with "filename." in the title. The location I want to search is: /u/*/*/*/stuff On the first computer I want to search: /u//*/*/stuff Right now I am doing... (1 Reply)
Discussion started by: msf5042
1 Replies

9. Shell Programming and Scripting

[Help]RegEx, Putty, Copy Files Insensitive Matching, SSH

Alright, basically we're in the whole where we can't tar/gzip a folder since its to big so how do I copy files to a new folder for example I got files from a-Z, i want to copy all files which starts with a A or a into another folder heres file structure ./backups/A ./backups/B... (11 Replies)
Discussion started by: Lamonte
11 Replies

10. Shell Programming and Scripting

Assistance with regex and config files

I am trying to write a shell script that will such in data from a config file. The script should mount device nodes that are contained in a config file in the following format: # filesystem type # read/write #device # Mount Point xfs w ... (1 Reply)
Discussion started by: pryker
1 Replies
Login or Register to Ask a Question