2

CORRECTED POST

@stribizhev is right. You cannot use look-aheads in bash regex. I used grep for that.

#!/bin/bash

fqdn=$1
result=`echo $fqdn | grep -P '(?=^.{1,254}$)(^(?>(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$)'`
if [[ -z "$result" ]]
then
    echo "$fqdn is NOT a FQDN"
else
    echo "$fqdn is a FQDN"
fi
exit

Thanks to the help of @stribizhev and < +OnlineCop > and < tureba > at http://webchat.freenode.net/?nick=regex101 .

ORIGINAL POST

I am trying to make this regex work to evaluate if the string is or not a valid FQDN with no success. I went through various searches with no success too.

For example, I copied a regex find at http://regexlib.com/REDetails.aspx?regexp_id=1319 and tried this way but is not working. What can be wrong?

#!/bin/bash

fqdn=$1
if [[ "$fqdn" =~ (?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$) ]]
then
        echo "$fqdn is a FQDN"
else
        echo "$fqdn is NOT a FQDN"
fi
exit
FedeKrum
  • 435
  • 1
  • 6
  • 15
  • A FQDN is described here https://en.wikipedia.org/wiki/Fully_qualified_domain_name . "www.aa.com" will be a matching example. "xxx" will not match. "@#$#.com" will not match. – FedeKrum Oct 02 '15 at 14:50
  • @stribizhev, I tried your example with no success. What would the if line be? `if [[ "$fqdn" =~ ^(?=.{1,254}$)(?:(?![0-9]+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$ ]]` – FedeKrum Oct 02 '15 at 14:54
  • I think you cannot use look-aheads in bash regex. You will need another pattern. Or use Perl. – Wiktor Stribiżew Oct 02 '15 at 15:10

1 Answers1

1

With one slight modification from the original, you can use grep -P instead of bash to accomplish this:

grep -P '(?=^.{1,254}$)(^(?>(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$)'

You can see the match here.

The difference, if you're interested, is to change (^(?:(?! to (^(?>(?! to prevent catastrophic backtracking.

zsh has support for a -pcre-match flag to be used within [...] and [[...]] as described on StackExchange which may be a way to accomplish this if you wish to use another shell than bash, although bash scripts are not always compatible with zsh scripts.

Community
  • 1
  • 1
OnlineCop
  • 4,019
  • 23
  • 35