1

I would like to validate true for the following URLs.

$a = '/foo-bar-tar';
$b = '/foo-&-tar2';
$a = '/foo-bar-tar.';
$a = '/foo-bar.[tar]';
$a = '/foo-bar-tar';

All in all, these are the characters I am willing to accept, in no special order:

/ - & [  ]  ( ) .

And of course letters and numbers:

a-z A-Z 0-9

The problem is that I can validate letters, numbers, and special characters like /.-, but I am having trouble validating ()[] – I guess because these are part of the regex language.

Here is the pattern I have so far:

^(/[a-z-A-z-0-9.]+)$

It matches letters, numbers, and ., but I don't know how to make it work for ()[].

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
robue-a7119895
  • 816
  • 2
  • 11
  • 31
  • 5
    Suggest that you read about __escaping__ "special characters" in regular expressions - http://www.regular-expressions.info/characters.html – Mark Baker Jan 12 '15 at 00:53

1 Answers1

1

Try the following adaptation of the pattern instead:

^\/[a-zA-Z0-9\-&\[\]().]+$

Regular expression visualization

Debuggex Demo (with unit tests for all the sample input strings in the question)

Key points:

  • ^ – matches the start of the input string
  • \/ – the opening / you expect
  • [a-zA-Z0-9\-&\[\]().]+ – one or more (+) alphanumeric (a-zA-Z0-9) or allowed special characters (\-&\[\]().) with -, [, and ] escaped in the character class due to their special meaning in that context
  • $ – matches the end of the input string

Also, I did not retain the grouping parens (i.e. ( and )) because they make little sense with the pattern constrained by ^ and $ and only one match of interest (i.e. the whole input string).

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
  • Hi, sorry. I thought Js and PHP regex was the same. Does this actually work on JS? I mean in stored as a Json? – robue-a7119895 Jan 12 '15 at 01:23
  • Much of what you can do with regexes will be the same in PHP and JS, but there are differences. For more info, I defer to a [related SO answer on the differences between regexes in PHP and JS](http://stackoverflow.com/a/9072234/1810429). – J0e3gan Jan 12 '15 at 01:27