1

I've found and want to use the following pattern ((ht|f)tp(s?)\:\/\/|~\/|\/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((\/?\w+\/)+|\/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?

Regular expressions 101 considers it a valid regex for javascript.

Yet when I try to use it in my ng-pattern it throws the following error:

SyntaxError: Invalid regular expression: /^((ht|f)tp(s?)://|~/|/)?([w]+:w+@)?([a-zA-Z]{1}([w-]+.)+([w]{2,5}))(:[d]{1,5})?((/?w+/)+|/?)(w+.[w]{3,4})?((?w+=w+)?(&w+=w+)*)?$/: Invalid group
    at new RegExp (native)

The exact way I'm implementing this is that I've defined the pattern in a configs file and then I'm loading it into the controller from which it is passed into the ng-pattern.

George Bora
  • 1,618
  • 6
  • 26
  • 45
  • 1
    You need to escape forward slashes by preceding with backward slash, ex `\/` – Tushar Nov 25 '15 at 14:43
  • 2
    You seem to have pasted it incorrectly. Try `ng-pattern="/^((ht|f)tps?\:\/\/|~\/|\/)?(\w+:\w+@)?([a-zA-Z]([\w-]+\.)+(\w{2,5}))(:\d{1,5})?((\/?\w+\/)+|\/?)(\w+\.\w{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?$/"`. – Wiktor Stribiżew Nov 25 '15 at 14:44
  • @stribizhev your pattern works if I put it directly in the template, but if I put it in the config and use it from there it doesn't work, why is this ? – George Bora Nov 25 '15 at 14:50
  • 1
    Probably because you need to provide it as a string: `^((ht|f)tps?://|~/|/)?(\\w+:\\w+@)?([a-zA-Z]([\\w-]+\\.)+(\\w{2,5}‌​))(:\\d{1,5})?((/?\\w+/)+|/?)(\\w+\\.\\w{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?$` – Wiktor Stribiżew Nov 25 '15 at 14:52
  • @stribizhev thank you very much now it works from config but now it doesn't want to validate https:google.com what's changed ? – George Bora Nov 25 '15 at 15:02
  • XY questions are not good. `https:google.com` was not matched by the initial regex. – Wiktor Stribiżew Nov 25 '15 at 15:26
  • @stribizhev could you please convert your "need to provide it as a string" comment into an answer I got it to work and I'd like to mark it as the accepted answer – George Bora Nov 25 '15 at 15:29

1 Answers1

1

To use the regex inside a config, you need to store it as a string. Since JS engine treats strings as C strings with escape sequences, the backslashes that escape regex metacharacters must be doubled:

^((ht|f)tps?://|~/|/)?(\\w+:\\w+@)?([a-zA-Z]([\\w-]+\\.)+(\\w{2,5}‌​))(:\\d{1,5})?((/‌​?\\w+/)+|/?)(\\w+\\.\\w{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?$

Also, I removed all unnecessary escaping: from /, from - in [\w-] (as at the end/start of the character class, - is treated as a literal hyphen), and removed unnecessary [...] from [\d] and [\w].

See the regex demo at regex101.com.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563