1

Regex is working fine with shell script as asked by me in different thread but when I use echo command as

 echo "2001:0Db8:85a3:0000:8a2e:0370:7334" | grep "^([0-9a-fA-F]{0,4}:){1,7}([0-9a-fA-F]){0,4}$"

There is no output and echo $? returns 1

Do regex not work with echo/grep?

codingenious
  • 8,385
  • 12
  • 60
  • 90
  • Use: `echo "2001:0Db8:85a3:0000:8a2e:0370:7334" | grep -E "^([0-9a-fA-F]{0,4}:){1,7}([0-9a-fA-F]){0,4}$"` for extended regex support in `grep` – anubhava Aug 08 '17 at 10:30

1 Answers1

2

You are using an ERE POSIX syntax here. Use -E option to make grep use POSIX ERE.

Or, escape ( and ) and { and } to make the pattern compatible with POSIX BRE:

echo "2001:0Db8:85a3:0000:8a2e:0370:7334" | grep "^\([0-9a-fA-F]\{0,4\}:\)\{1,7\}[0-9a-fA-F]\{0,4\}$"

See the online demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • `-r` in `grep` means recursive search. Only other option to support shown regex is `-P` (PCRE) – anubhava Aug 08 '17 at 10:39
  • 1
    @anubhava I am sorry, I mixed up `sed` and `grep`. – Wiktor Stribiżew Aug 08 '17 at 10:39
  • Yes I also thought so :) – anubhava Aug 08 '17 at 10:40
  • This doesn't work on solaris. Is there any other option I should add? – codingenious Aug 08 '17 at 11:10
  • @Batty From what I remember, you may have issues with it. Solaris `grep` does not seem to support limiting quantifiers. I do not have access to a Solaris OS though. If you have issues, please let me know, and I will re-vamp the pattern. – Wiktor Stribiżew Aug 08 '17 at 11:12
  • Take the regex [from here](https://regex101.com/r/UVHCPM/1), just remove all line breaks so that is becomes a long string pattern. It should be the same regex, with all limiting quantifiers unrolled. [This is how it works](https://regex101.com/r/dZN5Mq/1). – Wiktor Stribiżew Aug 08 '17 at 11:20
  • I found a previous [question about limiting quantifiers on SunOS](https://stackoverflow.com/questions/38822261/regex-failed-to-match-using-m-n-on-sunos/38833648#38833648). So, the only work around is to unroll these quantifiers. Note you may remove escaping ``\`` from `(` and `)` if you use `egrep`. – Wiktor Stribiżew Aug 08 '17 at 11:35
  • This is not a valid IPv6 address. – MaXi32 Jul 08 '21 at 10:28